java小学算术运算测试程序
时间: 2023-12-31 15:23:58 浏览: 125
算术运算测试程序.pdf
以下是一个Java小学算术运算测试程序的示例:
```java
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
public class ArithmeticTestProgram extends Frame implements ActionListener {
private Label label1, label2, label3, label4, label5, label6, label7, label8, label9, label10;
private TextField textField;
private Button button;
private ArrayList<String> questions;
private ArrayList<String> answers;
public ArithmeticTestProgram() {
setTitle("小学生四则运算测试系统-郑州轻工业大学-***-开发,****..");//设置标题
setLayout(new GridLayout(12, 1));
label1 = new Label("小学生四则运算测试系统");
label2 = new Label("请输入题目数量:");
textField = new TextField();
button = new Button("开始测试");
button.addActionListener(this);
add(label1);
add(label2);
add(textField);
add(button);
setSize(400, 300);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
int num = Integer.parseInt(textField.getText());
generateQuestions(num);
saveQuestionsToFile();
}
}
private void generateQuestions(int num) {
questions = new ArrayList<>();
answers = new ArrayList<>();
for (int i = 0; i < num; i++) {
int operand1 = (int) (Math.random() * 100);
int operand2 = (int) (Math.random() * 100);
int operator = (int) (Math.random() * 4);
String question = "";
String answer = "";
switch (operator) {
case 0:
question = operand1 + " + " + operand2 + " = ";
answer = String.valueOf(operand1 + operand2);
break;
case 1:
question = operand1 + " - " + operand2 + " = ";
answer = String.valueOf(operand1 - operand2);
break;
case 2:
question = operand1 + " * " + operand2 + " = ";
answer = String.valueOf(operand1 * operand2);
break;
case 3:
question = operand1 + " / " + operand2 + " = ";
answer = String.valueOf(operand1 / operand2);
break;
}
questions.add(question);
answers.add(answer);
}
}
private void saveQuestionsToFile() {
File file = new File("questions.txt");
try {
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
for (int i = 0; i < questions.size(); i++) {
String question = questions.get(i);
String answer = answers.get(i);
String line = question + answer + "\n";
bos.write(line.getBytes());
}
bos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
ArithmeticTestProgram program = new ArithmeticTestProgram();
}
}
```
阅读全文