java作业2

一:
代码:public class MethodOverload {
public static void main(String[] args) {
System.out.println("The square of integer 7 is " + square(7));
System.out.println("\nThe square of double 7.5 is " + square(7.5));
}

public static int square(int x) {
    return x * x;
}

public static double square(double y) {
    return y * y;
}

}
核心:
1. 识别图片中的Java代码结构

2. 分析代码中的关键特性

3. 解释方法重载的概念和应用

4. 总结代码的特殊之处
结果:
The square of integer 7 is 49

The square of double 7.5 is 56.25
结论:
1. 方法重载:代码中定义了两个同名的 square 方法,但参数类型不同(一个接收 int 参数,另一个接收 double 参数)

2. 参数多态性:根据传入参数的类型,Java编译器会自动选择合适的方法版本执行

3. 代码复用:通过方法重载实现了相同功能(计算平方)的不同参数版本,提高了代码的灵活性和可读性

二:
import java.util.Random;

public class ArithmeticGenerator {
public static void main(String[] args) {
// 生成30道题目
for (int i = 0; i < 30; i++) {
String question = generateQuestion();
System.out.println((i + 1) + ". " + question);
}
}

/**
 * 生成一道四则运算题目
 * @return 题目字符串(如"12 + 5 =")
 */
public static String generateQuestion() {
    Random random = new Random();
    int num1 = random.nextInt(20) + 1; // 1-20的随机整数
    int num2 = random.nextInt(20) + 1;
    String[] operators = {"+", "-", "×", "÷"};
    String operator = operators[random.nextInt(4)];

    // 处理减法(确保结果非负)
    if ("-".equals(operator)) {
        if (num1 < num2) {
            int temp = num1;
            num1 = num2;
            num2 = temp;
        }
    }

    // 处理除法(确保结果为整数)
    if ("÷".equals(operator)) {
        // 避免除以0
        while (num2 == 0 || num1 % num2 != 0) {
            num1 = random.nextInt(20) + 1;
            num2 = random.nextInt(20) + 1;
        }
    }

    // 构建题目字符串
    return num1 + " " + operator + " " + num2 + " =";
}

}

posted @ 2025-10-08 13:31  空气serf  阅读(7)  评论(0)    收藏  举报