簡體   English   中英

需要幫助的 Java 循環混淆

[英]Java loop confusion requiring assistance

所以我需要幫助,我正在嘗試輸入一個 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 
}

我想這就是你要找的。

    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,循環將終止。

如果要檢查而不區分大小寫,則應將 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則退出,否則返回到循環的第一行。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM