轉載自:IT學習者-螃蟹
一個方法A使用了Scanner,在裡面把它關閉了。然後又在方法B裡調用方法A之後就不能再用Scanner了Scanner in = new Scanner(System.in);
測試代碼如下:
importjava.util.Scanner;
public classItxxzScanner {//第一次輸入
public voidFistTime (){
Scanner sc= newScanner (System.in);int first =sc.nextInt();
System.out.println("first:"+first);
sc.close();
}//第二次輸入
public voidSecondTime(){
Scanner sc= newScanner (System.in);int second =sc.nextInt();
System.out.println("second:"+second);
sc.close();
}//測試入口
public static voidmain(String arg[]){
ItxxzScanner t= newItxxzScanner();
t.FistTime();
t.SecondTime();
}
}
運作後便抛出如下異常:

可以看出,在代碼第29行的時候報錯,抛出了 java.util.NoSuchElementException 異常,
下面我們來分析一下報錯的原因:
1、在 FistTime(){...} 使用sc.close();進行關閉處理,會把System.in也關閉了
2、當下次在SecondTime(){...}方法中再進行new Scanner (System.in)操作讀取的時候,因為輸入流已經關閉,是以讀取的值就是-1;
3、在Scanner 的readinput方法裡面有以下代碼:
try{
n=source.read(buf);
}catch(IOException ioe) {
lastException=ioe;
n= -1;
}if (n == -1) {
sourceClosed= true;
needInput= false;
}
4、因為讀到了-1就設定sourceClosed =true;neepinput=false;
5、在next方法裡面有以下代碼:
if(needInput)
readInput();elsethrowFor();
6、當needinput為false,就執行throwFor,是以再看throwFor
skipped = false;if ((sourceClosed) && (position ==buf.limit()))throw newNoSuchElementException();else
throw newInputMismatchException();
7、position 是目前讀取的内容在緩沖區中位置,因為讀取的是-1,是以position =0,而buf.limit()也等于0,是以就執行了throw new NoSuchElementException();