Scanner中用nextInt(輸入非數(shù)字),產(chǎn)生異常后再執(zhí)行輸入時(shí)的現(xiàn)象
package?test1; import?java.util.Scanner; public?class?test?{ Scanner?cmd?=?new?Scanner(System.in); String?[]?bookName?=?{"高數(shù)","數(shù)據(jù)結(jié)構(gòu)"}; public??int?inputCommand(){ int?command; try?{ command?=?cmd.nextInt(); return?command; }?catch?(Exception?e)?{ cmd?=?new?Scanner(System.in); return?-1; } } public?String?searchSerial()?throws?Exception{ System.out.println("輸入序號(hào):"); while(true) { try?{ int?serial?=?cmd.nextInt(); return?bookName[serial]; }catch(Exception?e)?{ // cmd?=?new?Scanner(System.in);??//如果注釋掉這一行就會(huì)發(fā)生圖中的錯(cuò)誤 throw?new?Exception("圖書不存在?s"); } } } public?static?void?main(String[]?args)?{ test?t?=new?test(); while(true) { try?{ System.out.println("輸入命令,1-按名稱查找,2-按序號(hào)查找"); int?i=t.inputCommand(); switch?(i) { case?2: { System.out.println("book:"+t.searchSerial()); break; } case?-1: { System.out.println("命令輸入錯(cuò)誤!請(qǐng)根據(jù)提示輸入數(shù)字命令!"); continue; } default: { System.out.println("命令輸入錯(cuò)誤!"); continue; } } break; }catch(Exception?e) { System.out.println(e.getMessage()); continue; } } } }
注釋的那一行cmd?=?new?Scanner(System.in);
取消注釋后結(jié)果
請(qǐng)大神給我講講內(nèi)部的原理,個(gè)人理解是輸入的值還被保存著但是不知道為啥在執(zhí)行一次就沒了。。
2018-02-24
在選擇圖書的時(shí)候拋出異常后,將異常捕獲后你有拋到外層了 然后在main的switch中被捕獲