java中用try如果catch到異常,怎麼把這個異常處理掉讓程式繼續執行
阿新 • • 發佈:2019-01-05
需要先將Scanner內的輸入清楚,不然就重複讀取了。簡單呼叫Scanner 的next()方法就可以了
測試已通過
package zhidao;
import java.util.Scanner;
public class Retry {
private int myInt;
private Scanner myScanner = new Scanner(System.in);
public int getInt() {
try {
System.out.println("請輸入法整數");
this.myInt = this.myScanner.nextInt();
} catch (Exception e) {
System.out.println("輸入錯誤,請輸入正確的數值!!!");
this.myScanner.next();
this.getInt();
}
return this.myInt;
}
public static void main(String[] args) {
Retry retry = new Retry();
System.out.println(retry.getInt());
}
}