You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java乘法测验程序优化:实现随机回复功能(switch语句)

为乘法测验程序添加随机回复功能

按照需求,我们需要让程序在学生答对/答错时随机选择对应回复,使用1-4的随机数配合switch语句实现。以下是修改后的完整代码:

package com.mycompany.multiplicationquiz;
import java.security.SecureRandom;
import java.util.Scanner;

public class MultiplicationQuiz {

    public static void main(String[] args) {
        generateRandomNumbers();
    }

    public static void generateRandomNumbers(){
        SecureRandom rand = new SecureRandom();
        int n1 = rand.nextInt(9) + 1;
        int n2 = rand.nextInt(9) + 1;
        
        generateQuestion(n1, n2, rand);
    }

    public static void generateQuestion (int n1, int n2, SecureRandom rand){
        Scanner sc = new Scanner (System.in);
        
        System.out.print("How much is " + n1 + " x " + n2 + " ?");
        int typedAnswer = sc.nextInt();
        
        if(typedAnswer == (n1*n2)) {
            int praiseChoice = rand.nextInt(4) + 1;
            switch(praiseChoice) {
                case 1:
                    System.out.println("Very Good!");
                    break;
                case 2:
                    System.out.println("Excellent!");
                    break;
                case 3:
                    System.out.println("Nice work!");
                    break;
                case 4:
                    System.out.println("Keep up the good work!");
                    break;
            }
            generateRandomNumbers();
        }else {
            int encouragementChoice = rand.nextInt(4) + 1;
            switch(encouragementChoice) {
                case 1:
                    System.out.println("No.Please try again");
                    break;
                case 2:
                    System.out.println("Wrong.Try once more.");
                    break;
                case 3:
                    System.out.println("Dont give up");
                    break;
                case 4:
                    System.out.println("No. Keep trying.");
                    break;
            }
            generateQuestion(n1, n2, rand);
        }
    }
}

关键修改说明

  • 复用SecureRandom实例:将生成随机数的实例传入generateQuestion方法,避免重复创建对象
  • 随机回复逻辑:
    • 答对时生成1-4的随机数,通过switch语句从指定的4条赞美语中选一条输出
    • 答错时同样生成1-4的随机数,通过switch语句从指定的4条鼓励语中选一条输出
  • 保留原有程序流程:答对后自动生成新题目,答错则重复当前题目直到答对

内容的提问来源于stack exchange,提问作者Ayaan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 10:52:48