Java循环混乱需要协助

时间:2019-06-15 16:58:16

标签: java

所以我需要帮助,我正在尝试输入Y / N程序,但它不接受大的'Y'或'N'。我还想做的另一件事是在按下'Y'/'y'之后,我试图使程序循环回到上面编写的代码。例如显示“ 123”的程序,我需要继续吗?是/否,如果输入是,它将返回以从头开始重新启动程序。请帮助我。

System.out.println("continue? Yes or no ");

       char check = s.next().charAt(0);

while (check != 'y' && response != 'n')// corrected this part, however need help with restarting the loop back to the first line of code in a loop {

  System.out.println("\nInvalid response. Try again.");
  check = s.next().charAt(0);

} if ((check == 'n') || (check == 'N')) {

    // I tried (check == 'n' || check == 'N') 
    System.out.println("Program terminated goodbye.");
    System.exit(0);

} else if (check == 'y') {
//need help with restarting the loop back to the first line of code in a loop 
}

3 个答案:

答案 0 :(得分:1)

我认为这就是您想要的。

list

在检查条件之前, char check; Scanner scanner = new Scanner(System.in); do { //your piece of code in here e.g. System.out.println("Printed 123"); System.out.println("Do you wish to continue?[Y/y] or [N/n]"); choice = scanner.next().charAt(0); }while (check =='Y' || check == 'y'); System.out.println("Program terminated goodbye."); 循环至少运行了一次,因此,当用户输入Y或y时,条件将为true,这意味着他们希望循环再次运行。如果用户输入其他任何值,则条件将为false,因为选择既不是Y也不是y,并且循环将终止。

答案 1 :(得分:0)

如果要检查时不区分大小写,则应将char转换为String,然后执行s1.equalsIgnoreCase(s2);

所以

while(true) {
    System.out.println("Continue? [Y/N]");
    char check_char = s.next().charAt(0);
    String check = Character.toString(check_char);

    while(check.equalsIgnoreCase("y") && !response.equalsIgnoreCase("n")) {
        System.out.println("\nInvalid response. Try again.");
        check = s.next().charAt(0);
    }

    if (check.equalsIgnoreCase("n")) {
        System.out.println("Program terminated goodbye.");
        System.exit(0);
    }
}

为了返回第一行,我使用了一个while循环,该循环会永远循环下去。

如果最后是 n ,则退出,否则返回循环的第一行。

答案 2 :(得分:0)

使用String.equals()比较字符串的值,==比较内存中的字符串。

相关问题