reprinted from: It learner-crab
A method a uses the scanner and closes it inside. Then after calling method A in method B, you can no longer use Scanner Scanner in = new Scanner (system.in);
The test code is as follows:
ImportJava.util.Scanner;/** * * @authorIt learner-crab * **/ Public classItxxzscanner {//First time input Public voidFisttime () {Scanner SC=NewScanner (system.in);intFirst =Sc.nextint (); System.out.println ("First:" +First ); Sc.close (); } //Second input Public voidSecondtime () {Scanner SC=NewScanner (system.in);intSecond =Sc.nextint (); System.out.println ("Second:" +second); Sc.close (); } //Test Portal Public Static voidMain (String arg[]) {Itxxzscanner T=NewItxxzscanner (); T.fisttime (); T.secondtime ();} }
After running, the following exception is thrown:
As you can see, in the 29th line of code error, throw a java.util.NoSuchElementException exception,
Let's analyze the cause of the error:
1. Use Sc.close () in Fisttime () {...}, close processing, and turn off system.in.
2, when the next time in Secondtime () {...} When the new Scanner (system.in) operation is read in the method, the read value is 1 because the input stream is closed;
3, in the scanner Readinput method has the following code:
Try=catch==-1;} if (n = =-1truefalse;}
4, because read 1 on the set sourceclosed =true;neepinput=false;
5. The following code is in the next method:
if (Needinput) readinput (); Else throwfor ();
6, when the Needinput is false, the execution of throwfor, so look at throwfor
false ; if ((sourceclosed) && (position = = Buf.limit ())) Throw New nosuchelementexception (); Else Throw New
7, position is the current read content in the buffer position, because the read is 1, so position = 0, and Buf.limit () is also equal to 0, therefore executed the throw new Nosuchelementexception ();
Java Learning Note Scanner error java.util.NoSuchElementException