我是Java新手,我正在嘗試制作一個猜謎游戲。在我的一行代碼中,我嘗試獲取用戶的輸入。但是,該程序似乎沒有運行該行代碼。為什么會發生這種事?問題出現在我的main方法中:Scanner input = new Scanner(System.in);System.out.println("Let's play a guessing game!");while (true){ // get a random number from 1 to 10 int random = (int) (Math.random() * 10) + 1; System.out.println("I am thinking of a number between 1 and 10."); System.out.print("What do you think it is? "); int guess = input.nextInt(); System.out.println((guess == random) ? "You are correct!":"You're wrong! The number was " + random); System.out.print("Play again? (Y/N)"); // this line is where the problem occurred. String play = input.nextLine(); if (play.equalsIgnoreCase("N")) break;}猜出數字后,程序會忽略詢問用戶是否想再次玩的那一行。為什么會發生這種情況?
1 回答

蝴蝶不菲
TA貢獻1810條經驗 獲得超4個贊
當您按“Enter”鍵時,該Scanner.nextInt
方法不會讀取換行符,因此在讀取該換行符Scanner.nextLine
后立即返回。
Scanner.nextLine
當您使用after anyScanner.next*
除其自身之外時,也會發生同樣的情況nextLine
。要解決這個問題,您可以Scanner.nextLine
在每個之后調用Scanner.nextInt
以消耗掛起的換行符。
添加回答
舉報
0/150
提交
取消