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