10.08课后作业
Java 程序设计——动手动脑与四则运算实验总结
学号:20253895 姓名:张一杭 班级:软件工程
本文整理本次课程中所有"动手动脑"问题以及课后实验性任务的分析与解答。
一、动手动脑:方法重载(Method Overload)
1. 题目代码
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;
}
}
2. 特殊之处分析
这段代码的特殊之处在于:同一个类中出现了两个同名方法 square,它们:
- 方法名相同:都是
square; - 参数列表不同:一个接收
int,一个接收double; - 返回值类型也随之不同(
int/double)。
这就是 Java 中的方法重载(Overloading)。在编译期,Java 根据调用时传入实参的类型,自动匹配对应的方法版本:
square(7)实参是int→ 调用square(int x);square(7.5)实参是double→ 调用square(double y)。
3. 运行结果
The square of integer 7 is 49
The square of double 7.5 is 56.25
小结:方法重载让一个函数名能够"按参数类型干不同类型的活",提高了代码的可读性和易用性。
二、动手动脑:浮点数为什么不能直接用 == 比较
1. 题目代码
double i = 0.0001;
double j = 0.00010000000000000001;
System.out.println(i == j); // 输出:true
2. 原因
计算机在内部以二进制浮点数(IEEE 754)存储小数,绝大多数十进制小数无法被精确表示,只能存储一个"足够接近"的近似值。上面两个数虽然写法相差了 17 个 0 后面的 1,但在 double 的有限精度下被舍入成了同一个二进制值,所以 i == j 的结果是 true。
3. 正确做法
比较两个浮点数是否相等时,不要直接用 ==,而要判断它们之差的绝对值是否小于一个允许的误差范围(epsilon):
if (Math.abs(i - j) < 1e-10) {
System.out.println("true");
} else {
System.out.println("false");
}
注意:课件中写的
Math.Abs(...)是 C# 写法;在 Java 中方法名是小写开头的Math.abs(...)。
三、课后实验:自动生成四则运算答题系统
1. 实验背景
老师要求程序员"二柱"每天给上小学二年级的孩子出 30 道四则运算题。我们需要写一个小程序自动完成这件事,并逐步升级为一个可在线答题、自动判分的小系统。
2. 需求(两个阶段)
阶段 1:能自动生成 30 道小学四则运算题。
阶段 2:在阶段 1 基础上完成以下功能,且要求用方法组织代码:
- 题目避免重复;
- 减法不允许出现负数(被减数 ≥ 减数);
- 乘法结果不允许出现四位数(即乘积 < 1000);
- 除法必须整除,不允许出现小数;
- 实现在线实时答题,答题结束后统计错题数和正确率;
- 增加倒计时功能,在指定时间内完成测试,超时未做完的题视为错题。
3. 设计思路
- 用
Random随机生成两个操作数a、b和运算符+ - * /; - 按规则约束各运算符:
- 减法:保证
a >= b; - 乘法:控制
a * b < 1000; - 除法:先随机出除数
b和商ans,再令被除数a = b * ans,从而保证整除;
- 减法:保证
- 用
Set<String>记录已生成的题目,遇到重复就重新生成; - 用 Swing 做图形界面:4 列排版题目,底部"查看得分"按钮;
- 用
javax.swing.Timer实现每秒倒计时,时间到自动判分; - 判分时逐题读取输入,空答案或格式错误按错题处理。
4. 完整代码(ArithmeticTest.java)
import javax.swing.*;
import java.awt.*;
import java.util.*;
/**
* 整数四则运算答题系统
* 学号: 20253895 姓名: 张一杭
*/
public class ArithmeticTest extends JFrame {
private static final int TOTAL = 30; // 题目总数
private static final int TIME_LIMIT = 300; // 限时 300 秒(5分钟)
private final String[] questions = new String[TOTAL];
private final int[] answers = new int[TOTAL];
private final JTextField[] inputs = new JTextField[TOTAL];
private final JLabel timerLabel = new JLabel();
private final JLabel scoreLabel = new JLabel(" ");
private final Timer timer;
private int timeLeft = TIME_LIMIT;
private boolean finished = false;
public ArithmeticTest() {
setTitle("整数四则运算测试");
setSize(960, 620);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout(10, 10));
// ---- 顶部: 学号姓名 + 倒计时 ----
JPanel top = new JPanel(new BorderLayout());
top.add(new JLabel(" 20253895 张一航 的第1轮测试"), BorderLayout.WEST);
timerLabel.setText("剩余时间: " + timeLeft + " s ");
top.add(timerLabel, BorderLayout.EAST);
add(top, BorderLayout.NORTH);
// ---- 中部: 30 道题, 4 列 ----
JPanel panel = new JPanel(new GridLayout(0, 4, 8, 8));
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
generateQuestions();
for (int i = 0; i < TOTAL; i++) {
JPanel row = new JPanel(new FlowLayout(FlowLayout.LEFT));
row.add(new JLabel((i + 1) + ". " + questions[i] + " ="));
inputs[i] = new JTextField(5);
row.add(inputs[i]);
panel.add(row);
}
add(panel, BorderLayout.CENTER);
// ---- 底部: 交卷按钮 + 得分 ----
JPanel bottom = new JPanel(new FlowLayout());
JButton btn = new JButton("查看得分");
btn.addActionListener(e -> grade());
bottom.add(btn);
bottom.add(scoreLabel);
add(bottom, BorderLayout.SOUTH);
// ---- 倒计时器 ----
timer = new Timer(1000, e -> {
timeLeft--;
timerLabel.setText("剩余时间: " + timeLeft + " s ");
if (timeLeft <= 0) {
timer.stop();
JOptionPane.showMessageDialog(this, "时间到!自动交卷");
grade();
}
});
timer.start();
setLocationRelativeTo(null);
setVisible(true);
}
/** 生成 30 道不重复、符合规则的四则运算题 */
private void generateQuestions() {
Set<String> seen = new HashSet<>();
Random rnd = new Random();
int count = 0;
while (count < TOTAL) {
int a = rnd.nextInt(100) + 1;
int b = rnd.nextInt(100) + 1;
char op = "+-*/".charAt(rnd.nextInt(4));
String q;
int ans;
switch (op) {
case '+':
ans = a + b;
q = a + " + " + b;
break;
case '-': // 减法不出现负数
if (a < b) { int t = a; a = b; b = t; }
ans = a - b;
q = a + " - " + b;
break;
case '*': // 乘积不允许四位数
a = rnd.nextInt(100) + 1;
b = rnd.nextInt(10) + 1;
if (a * b >= 1000) continue;
ans = a * b;
q = a + " × " + b;
break;
default: // 除法必须整除
b = rnd.nextInt(9) + 1;
ans = rnd.nextInt(10) + 1;
a = b * ans;
q = a + " ÷ " + b;
break;
}
if (seen.contains(q)) continue; // 避免重复
seen.add(q);
questions[count] = q;
answers[count] = ans;
count++;
}
}
/** 判分: 统计错题数与正确率 */
private void grade() {
if (finished) return;
finished = true;
timer.stop();
int correct = 0, wrong = 0;
for (int i = 0; i < TOTAL; i++) {
String text = inputs[i].getText().trim();
try {
if (Integer.parseInt(text) == answers[i]) correct++;
else wrong++; // 答错
} catch (NumberFormatException ex) {
wrong++; // 空答案 / 超时未做 -> 错题
}
}
double rate = correct * 100.0 / TOTAL;
String msg = "错题数: " + wrong + " 正确率: "
+ String.format("%.1f%%", rate);
scoreLabel.setText(msg);
JOptionPane.showMessageDialog(this, msg + "\n正确: " + correct + " / " + TOTAL);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(ArithmeticTest::new);
}
}
5. 运行效果
编译运行 ArithmeticTest 后弹出窗口:
- 顶部显示学号、姓名以及剩余倒计时;
- 窗口内以 4 列布局随机排列 30 道加减乘除题(减法不为负、乘法不满千、除法可整除、题目互不重复);
- 在输入框中实时作答,点击"查看得分"立即判分;
- 倒计时归零时自动交卷,未作答的题按错题处理;
- 结束后弹窗及底部标签显示错题数与正确率。
四、小结
| 实验点 | 关键知识点 |
|---|---|
| 方法重载 | 同名方法参数列表不同,编译期按实参类型绑定 |
| 浮点数比较 | 不能用 ==,应比较 Math.abs(a-b) < epsilon |
| 四则运算系统 | 随机数、集合去重、条件约束、Swing 界面、Timer 倒计时、方法封装 |

浙公网安备 33010602011771号