Java算术运算测试:功能要求:该程序实现十道100以内加减法数学 题,能根据题目计算出答案,与输入答案对比,判断做题是否正确, 最后计算分数用图形界面实现。并给出源代码
时间: 2024-03-16 07:47:30 浏览: 57
好的,下面是符合你要求的Java程序代码:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ArithmeticTest extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JLabel problemLabel = new JLabel("题目:");
private JLabel answerLabel = new JLabel("答案:");
private JTextField problemField = new JTextField(10);
private JTextField answerField = new JTextField(10);
private JButton submitBtn = new JButton("提交");
private JButton nextBtn = new JButton("下一题");
private int score = 0;
private int questionCount = 0;
public ArithmeticTest() {
setTitle("算术测试");
setSize(400, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
JPanel problemPanel = new JPanel();
problemPanel.add(problemLabel);
problemPanel.add(problemField);
problemPanel.add(answerLabel);
problemPanel.add(answerField);
JPanel buttonPanel = new JPanel();
buttonPanel.add(submitBtn);
buttonPanel.add(nextBtn);
add(problemPanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
submitBtn.addActionListener(this);
nextBtn.addActionListener(this);
generateQuestion();
}
private void generateQuestion() {
int num1 = (int)(Math.random() * 100);
int num2 = (int)(Math.random() * 100);
int operator = (int)(Math.random() * 2);
String operatorStr = operator == 0 ? "+" : "-";
int result = operator == 0 ? num1 + num2 : num1 - num2;
problemField.setText(num1 + " " + operatorStr + " " + num2 + " = ");
answerField.setText("");
answerField.requestFocus();
questionCount++;
}
private void checkAnswer() {
String answerStr = answerField.getText();
if (answerStr.length() == 0) {
JOptionPane.showMessageDialog(this, "请输入答案");
return;
}
int answer = Integer.parseInt(answerStr);
int num1 = Integer.parseInt(problemField.getText().split(" ")[0]);
int num2 = Integer.parseInt(problemField.getText().split(" ")[2]);
int operator = problemField.getText().split(" ")[1].equals("+") ? 0 : 1;
int result = operator == 0 ? num1 + num2 : num1 - num2;
if (answer == result) {
score++;
JOptionPane.showMessageDialog(this, "回答正确");
} else {
JOptionPane.showMessageDialog(this, "回答错误");
}
}
private void showScore() {
JOptionPane.showMessageDialog(this, "你的得分是: " + score + "/" + questionCount);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == submitBtn) {
checkAnswer();
} else if (e.getSource() == nextBtn) {
generateQuestion();
}
if (questionCount == 10) {
showScore();
System.exit(0);
}
}
public static void main(String[] args) {
ArithmeticTest test = new ArithmeticTest();
test.setVisible(true);
}
}
```
这个程序使用了Java的Swing库来实现图形界面,可以在命令行或者集成开发环境中运行。运行程序后,会随机生成10道100以内的加减法题目,你需要输入答案并点击提交按钮来检查答案是否正确,点击下一题按钮可以跳转到下一道题目。在最后一道题目答完后,程序会弹出对话框显示你的得分,并退出程序。
阅读全文