1. 程式人生 > >while try catch無限迴圈

while try catch無限迴圈

   
Scanner console= new Scanner(System.in); 
 private int CatchInput() {
while (true) {
try {
System.out.println("------輸入id------");
return console.nextInt();
} catch (InputMismatchException e) {
System.out.println("------輸入錯誤------");
}
}
}
當console型別輸入錯誤 執行catch語句 通過while迴圈重新執行try語句 會使用上一次的結果直接進入catch 以此往復無限迴圈


 
 private int CatchInput() {
while (true) {
try {
          Scanner console= new Scanner(System.in);  
                System.out.println("------輸入id------");
return console.nextInt();
} catch (InputMismatchException e) {
System.out.println("------輸入錯誤------");
}
}
}
將Scanner的定義放入try語句中即可