首页 > 解决方案 > 爪哇。做一个问题重新问你是否弄错了

问题描述

我是java新手,所以我很害怕。基本上我正在做一个多项选择测验。

但我的问题是,即使你答错了问题,它也会转到下一个问题,我希望它再次问同样的问题,就像一个循环一样。我试图让它工作,但我做不到,它可能非常简单易行。如果有人可以提供帮助,那就太酷了!

它说什么是 9+10?1. 19 2. 21 3. 18

当前代码:

iAnswer = Integer.parseInt(System.console().readLine());

if (iAnswer == 1) {
  System.out.println(" ");
  System.out.println("Correct");
}
else {
  iLives -= 1;
  System.out.println(" ");
  System.out.println("Incorrect");
}

(当你答错问题时,你会失去生命,但我认为这并不重要)

标签: java

解决方案


我不确定这是否是您要求的,但我想出了这个!

 //get input from console
 Scanner scanner = new Scanner(System.in);
 //create a loop to keep
    while (true) {
        //get 2 random number on value(0 - 20)
        int n1 = (int) (Math.random() * 20 + 1);
        int n2 = (int) (Math.random() * 20 + 1);
        //correct Answer is saved in correctAns value
        int correctAns = n1 + n2;
        System.out.println("What is the anwser of : ");
        System.out.print(n1 + " + " + n2 + " = ");
        //get the answer from user input
        int ans = scanner.nextInt();
        //if user input is equal to current Answer
        if (ans == correctAns) {
            System.out.println("Congrats next question !");
        } else {
            //if user input is not equal to currentAns
            boolean condition = true;
            //create another loop where user has to answer right to get to 
            //the next question
            while (condition) {
                System.out.println("What is the anwser of : ");
                System.out.print(n1 + " + " + n2 + " = ");
                ans = scanner.nextInt();
                //if user input is equal to currentAns
                if (ans == correctAns) {
                    //stop the loop and continue to the other question
                    condition = false;
                } else {
                    // if user input is not equal to currentAns keep asking
                    // the same question
                    condition = true;
                }
            }
        }
    }

推荐阅读