首页 > 解决方案 > 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 
}

标签: java

解决方案


我想这就是你要找的。

    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.");

do-while检查条件之前,循环至少运行一次,因此当用户输入 Y 或 y 时,条件将为真,这意味着他们希望循环再次运行。如果用户输入任何其他值,则条件将变为假,因为选择既不是 Y 也不是 y 并且循环将终止。


推荐阅读