在输入正确的输入之前,如何让扫描仪继续询问输入? Java的

时间:2017-11-23 15:00:43

标签: java loops

我目前正在为小学生开发数学游戏,我试图让用户不断输入答案,直到问题得到解决。然后我希望他们转到下一个问题。当我运行下面的代码时,它给了我2次机会输入正确的答案,但它不会显示我的“正确的”#39;第二次发出消息。

{{1}}

This is a photo of my code

5 个答案:

答案 0 :(得分:0)

将输入的代码置于do while循环中,并在while条件下检查输出是否正确

do{
    statements(s)
}while(condition);

答案 1 :(得分:0)

while(userAnswer != realAnswer){
    System.out.print("Wrong answer. Try again: ");
    userAnswer = in.nextInt(); // or whatever you need instead of int
}

答案 2 :(得分:0)

你必须使用while循环。此循环重复其“内容”(大括号内的代码),而其条件(正常括号内的布尔值)为真。在这种情况下,条件是输入 正确,“内容”是打印“再试一次”的代码。信息。 这是一个演示:

Scanner scanner = new Scanner(System.in);
while (scanner.nextDouble() != 7) {
    System.out.println("Try again!");
}
System.out.println("Correct!");

答案 3 :(得分:0)

声明一个标志值。并且最初将其设置为0. flag = 0;

    do{
     if(r5q1==7){
     flag=1;
     break;
     }
     else{
     continue;
      }
    }while(r5q1!=7);

    if(flag==1)
    {
    System.out.println("Correct");
    }
    else
    {
    System.out.println("Wrong");
    }

答案 4 :(得分:0)

谢谢管理员!这非常有效!

import java.util.Scanner;
public class test{
   public static void main (String[]args){
      Scanner kb= new Scanner(System.in);
      double r5q1,r5q2,r5q3,r5q4,r5q5;
      System.out.println("Welcome to the money level.. This is the last and most difficult level!");
      //Question 1
      System.out.println("Question 1: I have $10.00 and I buy a candy bar for $3.00. How much change will I get?");
      r5q1=kb.nextDouble();
         do{
            System.out.println("Try again!");
            r5q1=kb.nextDouble();
         }while(r5q1!=7);//This is the answer to the question
      System.out.println("Correct!");

      //Question 2
      System.out.println("Question 2: I have $15.00 and I buy 5 apples for $1.00 each. How much change will I get?");
      r5q1=kb.nextDouble();
         do{
            System.out.println("Try again!");
            r5q2=kb.nextDouble();
         }while(r5q2!=10); //This is the answer to the question
      System.out.println("Correct!");
   }
}