我已經使用 java 幾個星期了,想嘗試制作我的第一個小游戲。我所擁有的一切都工作正常,直到我嘗試添加再次播放功能??雌饋硭皇翘^了底部的一小部分代碼,我不明白為什么。我嘗試過移動代碼的不同部分,但無法弄清楚為什么它不起作用。public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("You have 10 tries to correctly guess a random number between 1 and 10. Good luck! \n" + "After you have entered a number, press ENTER to see if you won."); boolean play; play = true; do { int tries = 10, triesLeft = 0, triesUsed = 0; String YorN; do { System.out.print("\nEnter A Number: "); int numInp = scan.nextInt(); int randomNumber = (int)(Math.random()*9) + 1; System.out.println("The number was " + randomNumber); if(numInp == randomNumber) { System.out.println("\nYou Win! Great job."); triesLeft = --tries; triesUsed = 10 - triesLeft; tries = -1; } else { System.out.println("Try Again..."); tries --; } } while( tries > 0); String playAgain = (" Feel free to play again soon!"); if(tries == 0) { System.out.println("\nOut of tries :( You lose loser " + playAgain); } if(tries == -1) { System.out.println("\nYou used " + triesUsed + " tries and had " + triesLeft + " tries left! :)" + playAgain); } System.out.print("\nDo you want to play again? Y or N?"); YorN = scan.nextLine(); if (YorN == ("Y") || YorN == ("y")) { play = true; } else if (YorN == ("N") || YorN == ("n")) { play = false; } else {} } while(play = true); if (play = false){ System.out.println("\nGood Bye"); }}當我運行代碼時,這個系統似乎沒有做任何事情:YorN = scan.nextLine(); if (YorN == ("Y") || YorN == ("y")) { play = true; } else if (YorN == ("N") || YorN == ("n")) { play = false; } else {}這是我運行時看到的內容:你贏了!做得好。您已經嘗試了 5 次,還剩 5 次嘗試!:) 很快就可以再次玩了!你想再玩一次嗎?是還是否?輸入號碼:它沒有給我一個應該輸入 y 或 n 的位置。如果有人知道為什么我會非常感謝你的幫助
1 回答

白板的微信
TA貢獻1883條經驗 獲得超3個贊
nextInt() 或 next() 方法不讀取 Enter。通常在數字之后您必須按 Enter 鍵,而上述方法尚未準備好。避免這種情況的排序方式是保留 1 個額外的 sc.nextLine() 方法調用。它將讀取并丟棄輸入。
scan.nextLine();
YorN = scan.nextLine();
if (YorN == ("Y") || YorN == ("y"))
{
play = true;
}
else if (YorN == ("N") || YorN == ("n"))
{
play = false;
}
else {}
添加回答
舉報
0/150
提交
取消