關(guān)于輸入判斷問題,請(qǐng)指導(dǎo)
在創(chuàng)建用戶的playerCreate方法中在接受用戶ID的輸入時(shí)我想實(shí)現(xiàn)判斷用戶輸入的ID是否為大于0的整數(shù),如果輸入的ID是非整型或者小于0時(shí)則拋出"請(qǐng)輸入一個(gè)正整數(shù)ID值:"的異常提示,并等待用戶重新輸入。
如果我用這樣一段代碼:
System.out.println("請(qǐng)輸入第"+index+"名玩家ID:");
while (ID<0) {
? ?try {
? ? ? ?ID = scanner.nextInt();
? ?} catch (Exception e) {
? ? ? ?System.out.println("請(qǐng)輸入一個(gè)正整數(shù)ID值:");
? ?}
}其中scanner是定義好的變量Scanner scanner=new Scanner(System.in),但是在執(zhí)行時(shí)當(dāng)輸入非法字符時(shí)出現(xiàn)如下情況:
請(qǐng)輸入第1名玩家ID:
a
請(qǐng)輸入一個(gè)正整數(shù)ID值:
請(qǐng)輸入一個(gè)正整數(shù)ID值:
請(qǐng)輸入一個(gè)正整數(shù)ID值:
請(qǐng)輸入一個(gè)正整數(shù)ID值:
請(qǐng)輸入一個(gè)正整數(shù)ID值:
請(qǐng)輸入一個(gè)正整數(shù)ID值:
程序會(huì)不斷的拋出異常提示,而不再中斷接受新的輸入,而用如下代碼
????????do {
? ? ? ? ? ? ? ?try {
? ? ? ? ? ? ? ? ? ?scanner = new Scanner(System.in);
? ? ? ? ? ? ? ? ? ?ID = scanner.nextInt();
? ? ? ? ? ? ? ? ? ?if(ID<0){
? ? ? ? ? ? ? ? ? ? ? ?System.out.println("請(qǐng)輸入一個(gè)正整數(shù)ID值:");
? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ?} catch (Exception e) {
? ? ? ? ? ? ? ? ? ?System.out.println("請(qǐng)輸入一個(gè)正整數(shù)ID值:");
? ? ? ? ? ? ? ?}
? ? ? ? ? ?} while (ID<0);
即把scanner的賦值放到try結(jié)構(gòu)(只要是while結(jié)構(gòu)內(nèi)都行)內(nèi)了,程序執(zhí)行就正常了,請(qǐng)問一下為什么scanner的賦值在try結(jié)構(gòu)內(nèi)和在while循環(huán)外對(duì)程序的執(zhí)行到底產(chǎn)生了什么影響,為什么在while循環(huán)外當(dāng)出現(xiàn)異常時(shí)就不再接受新的輸入了。
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每次都創(chuàng)建了新的對(duì)象,自然之前的buffer 是空的