亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么程序無法獲取用戶的輸入?

為什么程序無法獲取用戶的輸入?

德瑪西亞99 2024-01-05 15:11:21
我是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以消耗掛起的換行符。


查看完整回答
反對 回復 2024-01-05
  • 1 回答
  • 0 關注
  • 125 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號