Java Learning Note Scanner error java.util.NoSuchElementException

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.