用Java写一个程序,并用GUI实现,程序用字符界面实现十道100以内加减乘除法数学题的自动生成,能根据题目计算出答案,与输入答案对比,判断做题是否正确,最后能计算出分数。
时间: 2024-06-14 09:05:02 浏览: 97
用Java编写的可以进行加减乘除计算的GUI计算器
5星 · 资源好评率100%
以下是用Java编写的程序,并使用GUI实现的十道100以内加减乘除法数学题的自动生成,并能计算出答案并与输入答案对比,判断做题是否正确,并最后计算出分数的示例:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class MathQuizGUI extends JFrame {
private JLabel questionLabel;
private JTextField answerField;
private JButton submitButton;
private JLabel resultLabel;
private int score;
public MathQuizGUI() {
setTitle("Math Quiz");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(4, 1));
questionLabel = new JLabel();
add(questionLabel);
answerField = new JTextField();
add(answerField);
submitButton = new JButton("Submit");
submitButton.addActionListener(new SubmitButtonListener());
add(submitButton);
resultLabel = new JLabel();
add(resultLabel);
generateQuestion();
setVisible(true);
}
private void generateQuestion() {
Random random = new Random();
int num1 = random.nextInt(100) + 1;
int num2 = random.nextInt(100) + 1;
int operator = random.nextInt(4);
String operatorStr;
int answer;
switch (operator) {
case 0:
operatorStr = "+";
answer = num1 + num2;
break;
case 1:
operatorStr = "-";
answer = num1 - num2;
break;
case 2:
operatorStr = "*";
answer = num1 * num2;
break;
case 3:
operatorStr = "/";
answer = num1 / num2;
break;
default:
operatorStr = "+";
answer = num1 + num2;
break;
}
questionLabel.setText(num1 + " " + operatorStr + " " + num2 + " = ");
answerField.setText("");
resultLabel.setText(""); score = 0;
}
private class SubmitButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
try {
int userAnswer = Integer.parseInt(answerField.getText());
int correctAnswer = getCorrectAnswer(questionLabel.getText());
if (userAnswer == correctAnswer) {
resultLabel.setText("Correct!");
score++;
} else {
resultLabel.setText("Incorrect!");
}
generateQuestion();
} catch (NumberFormatException ex) {
resultLabel.setText("Invalid input!");
}
}
private int getCorrectAnswer(String question) {
String[] parts = question.split(" ");
int num1 = Integer.parseInt(parts[0]);
int num2 = Integer.parseInt(parts[2]);
String operator = parts[1];
switch (operator) {
case "+":
return num1 + num2;
case "-":
return num1 - num2;
case "*":
return num1 * num2;
case "/":
return num1 / num2;
default:
return 0;
}
}
}
}
public class Main {
public static void main(String[] args) {
MathQuizGUI mathQuizGUI = new MathQuizGUI();
}
}
```
阅读全文