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

為了賬號安全,請及時綁定郵箱和手機立即綁定

關于輸入判斷問題,請指導

在創建用戶的playerCreate方法中在接受用戶ID的輸入時我想實現判斷用戶輸入的ID是否為大于0的整數,如果輸入的ID是非整型或者小于0時則拋出"請輸入一個正整數ID值:"的異常提示,并等待用戶重新輸入。

如果我用這樣一段代碼:

System.out.println("請輸入第"+index+"名玩家ID:");
while (ID<0) {
? ?try {
? ? ? ?ID = scanner.nextInt();
? ?} catch (Exception e) {
? ? ? ?System.out.println("請輸入一個正整數ID值:");
? ?}
}其中scanner是定義好的變量Scanner scanner=new Scanner(System.in),但是在執行時當輸入非法字符時出現如下情況:
請輸入第1名玩家ID:
a
請輸入一個正整數ID值:
請輸入一個正整數ID值:
請輸入一個正整數ID值:
請輸入一個正整數ID值:
請輸入一個正整數ID值:
請輸入一個正整數ID值:

程序會不斷的拋出異常提示,而不再中斷接受新的輸入,而用如下代碼
????????do {
? ? ? ? ? ? ? ?try {
? ? ? ? ? ? ? ? ? ?scanner = new Scanner(System.in);
? ? ? ? ? ? ? ? ? ?ID = scanner.nextInt();
? ? ? ? ? ? ? ? ? ?if(ID<0){
? ? ? ? ? ? ? ? ? ? ? ?System.out.println("請輸入一個正整數ID值:");
? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ?} catch (Exception e) {
? ? ? ? ? ? ? ? ? ?System.out.println("請輸入一個正整數ID值:");
? ? ? ? ? ? ? ?}
? ? ? ? ? ?} while (ID<0);
即把scanner的賦值放到try結構(只要是while結構內都行)內了,程序執行就正常了,請問一下為什么scanner的賦值在try結構內和在while循環外對程序的執行到底產生了什么影響,為什么在while循環外當出現異常時就不再接受新的輸入了。


正在回答

1 回答

String java.util.Scanner.next(Pattern pattern)

Returns the next token if it matches the specified pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext(Pattern) returned true. If the match is successful, the scanner advances past the input that matched the pattern.


另外你在try 里面 scanner每次都創建了新的對象,自然之前的buffer 是空的

0 回復 有任何疑惑可以回復我~

舉報

0/150
提交
取消
Java入門第三季
  • 參與學習       409767    人
  • 解答問題       4543    個

Java中你必須懂得常用技能,不容錯過的精彩,快來加入吧

進入課程

關于輸入判斷問題,請指導

我要回答 關注問題
微信客服

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

幫助反饋 APP下載

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

公眾號

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