1-解決java Scanner出現 java.util.NoSuchElementException
阿新 • • 發佈:2018-11-09
起因:在函式中新建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();