起因:在函數中新建scanner對象,然后多次調用此方法出現上述異常
原因:Scanner(system.in)在Scanner中接受的是鍵盤 輸入,當調用close()方法時
Scanner的關閉會導致System.in的關閉,System.in是標准輸入(鍵盤輸入),只能關一次,關閉后不能再打開。
解決辦法1:在主函數的聲明,然后作為參數傳入方法中
解決辦法2:
查看scanner源碼
// Boolean indicating if this scanner has been closed private boolean closed = false; public void close() { if (closed) return; if (source instanceof Closeable) { try { ((Closeable)source).close();//將會關閉流 } catch (IOException ioe) { lastException = ioe; } } sourceClosed = true; source = null; closed = true; }
直接在函數中用反射改變closed的值,實現永遠不關閉
public void scanner() throws NoSuchFieldException, IllegalAccessException, InstantiationException { Scanner my=new Scanner(System.in); a=my.nextInt(); b=my.nextInt(); c=my.nextInt(); Class clazz =Scanner.class; Field field = clazz.getDeclaredField("closed"); field.setAccessible(true); field.set(my,true); my.close(); }
當想要關閉的時候,再使用反射改變為false,調用scanner.close();