關于輸入判斷問題,請指導
在創建用戶的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循環外當出現異常時就不再接受新的輸入了。
2015-05-07
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 是空的