课后作业1
动手动脑:这段代码展示了 Java 中的方法重载特性。
特殊之处:
- 同名方法:类中有两个都叫
square的方法 - 参数类型不同:
square(int x)接收 int 类型参数
square(double y)接收 double 类型参数 - 返回值类型不同:
一个返回int
一个返回double
运行机制:
System.out.println("The square of integer 7 is " + square(7));
// 调用 square(int x) 方法,因为 7 是 int 类型
System.out.println("\nThe square of double 7.5 is " + square(7.5));
// 调用 square(double y) 方法,因为 7.5 是 double 类型
输出结果:
The square of integer 7 is 49
The square of double 7.5 is 56.25
这就是 Java 多态性的一种体现——同一个方法名可以根据参数类型执行不同的操作。
课后实验性作业:import java.util.Scanner;
import java.util.HashSet;
public class number {
static Scanner sc = new Scanner(System.in);
static HashSet
// 检查题目是否重复
public static boolean isDuplicate(String question) {
if (generatedQuestions.contains(question)) {
return true;
} else {
generatedQuestions.add(question);
return false;
}
}
public static int subtraction() {
int a, b;
String question;
do {
a = (int)(Math.random() * 100);
b = (int)(Math.random() * 100);
question = a + "-" + b; // 生成题目字符串
} while (a < b || isDuplicate(question)); // 检查是否重复
System.out.print(a + "-" + b + "=");
return a - b;
}
public static int division() {
int a, b;
String question;
do {
b = (int)(Math.random() * 99) + 1;
a = (int)(Math.random() * 100);
question = a + "/" + b; // 生成题目字符串
} while (a % b != 0 || a == 0 || isDuplicate(question)); // 检查是否重复
System.out.print(a + "/" + b + "=");
return a / b;
}
public static int multiplication() {
int a, b, c;
String question;
do {
a = (int)(Math.random() * 100);
b = (int)(Math.random() * 100);
c = a * b;
question = a + "*" + b; // 生成题目字符串
} while (c > 9999 || isDuplicate(question)); // 检查是否重复
System.out.print(a + "*" + b + "=");
return c;
}
// 新增加法方法,也加入重复检查
public static int addition() {
int a, b;
String question;
do {
a = (int)(Math.random() * 100);
b = (int)(Math.random() * 100);
question = a + "+" + b; // 生成题目字符串
} while (isDuplicate(question)); // 检查是否重复
System.out.print(a + "+" + b + "=");
return a + b;
}
public static int tf(int c) {
int num = sc.nextInt();
if(num != c) {
return 1;
} else {
return 0;
}
}
public static void main(String[] args) {
int n = 0;
generatedQuestions.clear(); // 清空题目集合,开始新的测试
for(int i = 0; i < 30; i++) {
int c;
switch((int)(Math.random() * 4)) {
case 0: // 加法
c = addition();
n += tf(c);
break;
case 1: // 减法
c = subtraction();
n += tf(c);
break;
case 2: // 乘法
c = multiplication();
n += tf(c);
break;
case 3: // 除法
c = division();
n += tf(c);
break;
}
}
System.out.println("错误题目数量: " + n);
System.out.println("正确率: " + (100 - n / 30.0 * 100) + "%");
sc.close();
}
}

浙公网安备 33010602011771号