加减法混合类的设计
-
Question类用来提供生成习题的方法,Quiz类进行题目和得分的管理
Question 类:
generateQuestion(): 生成随机的加减法题目
getQuestion(): 获取题目字符串
getAnswer(): 得正确答案
Quiz 类:
addQuestion(Question question): 添加题目
startQuiz(): 开始答题
getScore(): 获取得分
questions: 存储题目的列表
QuizApp 类
main(): 程序入口
class Question {
private int num1;
private int num2;
private String operator;
public Question() {
generateQuestion();
} // 生成随机的加减法题目
public void generateQuestion() {
Random rand = new Random();
num1 = rand.nextInt(100); // 生成0到99之间的随机数
num2 = rand.nextInt(100);
operator = rand.nextBoolean() ? "+" : "-"; // 随机选择加法或减法
}
public String getQuestion() {
return num1 + " " + operator + " " + num2 + " = ?";
}
public int getAnswer() {
return operator.equals("+") ? num1 + num2 : num1 - num2;
}
}
// Quiz类用于管理题目和得分
class Quiz {
private List<Question> questions;
private int score;
public Quiz() {
questions = new ArrayList<>();
score = 0;
}
public void addQuestion(Question question) {
questions.add(question);
}
public void startQuiz() {
Scanner scanner = new Scanner(System.in);
for (Question question : questions) {
System.out.println(question.getQuestion());
int userAnswer = scanner.nextInt();
if (userAnswer == question.getAnswer()) {
System.out.println("正确!");
score++;
} else {
System.out.println("错误,正确答案是: " + question.getAnswer());
}
}
System.out.println("你的得分是: " + score + "/" + questions.size());
scanner.close();
}
public int getScore() {
return score;
}
}// QuizApp类为程序入口
public class QuizApp {
public static void main(String[] args) {
Quiz quiz = new Quiz();
// 生成10道题目
for (int i = 0; i < 10; i++) {
Question question = new Question();
quiz.addQuestion(question);
}
quiz.startQuiz();
}
}