簡體   English   中英

嘗試為Java游戲創建“再次玩”

[英]Trying to create “Play Again” for a game in Java

出於某種原因,使用此代碼,我運行的測試表明該程序完全跳過了nextLine對用戶輸入的請求,並將其注冊為空白以進行第一次迭代。 之后,它將返回while循環的開始並接受輸入,但是無論我鍵入什么內容(無論是y或Y,是n還是n),它都會轉到else語句。 我不明白我在做什么錯,求助!

private static boolean promptForPlayAgain(Scanner inScanner) {

    boolean play = true;
    int test = 0;

    while(test == 0)
    {   
        System.out.println("Would you like to play again [Y/N]?:");
        String input = inScanner.nextLine();
        System.out.println(input);

        if (input == "y" || input == "Y")
        {
            test++;
        }
        else if (input == "n" || input == "N")
        {
            play = false;
            test++;
        }
        else
        {
            System.out.println("ERROR! Only 'Y' or 'N' allowed as input!");
        }
    }
    return play;
}

由於某種原因,我忘記了(很抱歉),輸入的第一行有時為空,請在定義input以跳過該空行之前添加inScanner.nextLine()

根據你們所說的技巧,我已經編輯並運行了現在可以運行的代碼。 非常感謝你們!

private static boolean promptForPlayAgain(Scanner inScanner) {

    boolean play = true;
    int test = 0;

    while(test == 0)
    {   
        System.out.println("Would you like to play again [Y/N]?:");
        inScanner.nextLine();
        String input = inScanner.nextLine();

        if (input.equals("y") || input.equals("Y") )
        {
            test++;
        }
        else if (input.equals("n") || input.equals("N") )
        {
            play = false;
            test++;
        }
        else
        {
            System.out.println("ERROR! Only 'Y' or 'N' allowed as input!");
        }
    }
    return play;
}

暫無
暫無

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

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