使用while循环进行数据验证时出现问题

时间:2019-04-07 16:50:39

标签: java while-loop

我已经声明扫描仪,开始

System.out.println();
System.out.println("Type the word \"Start\" when your ready to begin the quiz");
start = input.nextLine();
input.nextLine();
while(!start.equals("start")){
  System.out.println("Make sure you read the question and try again");
  start = input.nextLine();
}

我希望输入“开始”,而while循环将退出,但我必须输入两次“开始”才能退出while循环

1 个答案:

答案 0 :(得分:0)

您可以使用do - while循环。它不同于while循环,因为它首先执行代码,然后评估while语句中设置的条件。

    System.out.println();
    System.out.println("Type the word \"start\" when your ready to begin the quiz");
    String start, answer;
    Scanner input = new Scanner(System.in);
    do {
        start = input.nextLine();
        if(!start.equals("start")) {
            System.out.println("Make sure you read the question and try again");
        } else {
            System.out.println("Enter the answer here: ");
            answer = input.nextLine();
        }
    } while (!start.equals("start"));