轉載自:IT學習者-螃蟹java
一個方法A使用了Scanner,在裏面把它關閉了。而後又在方法B裏調用方法A以後就不能再用Scanner了Scanner in = new Scanner(System.in);學習
測試代碼以下:測試
import java.util.Scanner; /** * * @author IT學習者-螃蟹 * * */ public class ItxxzScanner { //第一次輸入 public void FistTime (){ Scanner sc = new Scanner (System.in); int first = sc.nextInt(); System.out.println("first:"+first); sc.close(); } //第二次輸入 public void SecondTime(){ Scanner sc = new Scanner (System.in); int second = sc.nextInt(); System.out.println("second:"+second); sc.close(); } //測試入口 public static void main(String arg[]){ ItxxzScanner t = new ItxxzScanner(); t.FistTime(); t.SecondTime(); } }
運行後便拋出以下異常:spa
能夠看出,在代碼第29行的時候報錯,拋出了 java.util.NoSuchElementException 異常,code
下面咱們來分析一下報錯的緣由:blog
一、在 FistTime(){...} 使用sc.close();進行關閉處理,會把System.in也關閉了ip
二、當下次在SecondTime(){...}方法中再進行new Scanner (System.in)操做讀取的時候,由於輸入流已經關閉,因此讀取的值就是-1; input
三、在Scanner 的readinput方法裏面有如下代碼:it
try { n = source.read(buf); } catch (IOException ioe) { lastException = ioe; n = -1; } if (n == -1) { sourceClosed = true; needInput = false; }
四、由於讀到了-1就設置sourceClosed =true;neepinput=false;io
五、在next方法裏面有如下代碼:
if (needInput) readInput(); else throwFor();
六、當needinput爲false,就執行throwFor,所以再看throwFor
skipped = false; if ((sourceClosed) && (position == buf.limit())) throw new NoSuchElementException(); else throw new InputMismatchException();
七、position 是當前讀取的內容在緩衝區中位置,由於讀取的是-1,所以position =0,而buf.limit()也等於0,所以就執行了throw new NoSuchElementException();