Scanner reports java.util.NoSuchElementException

Code:

import java.util.Scanner;
public class Test_Scanner {
    
    
	public static void main(String[] args) {
    
    
		Scanner sc = new Scanner(System.in);
		String input = sc.next();
		sc.close();
		Scanner in = new Scanner(System.in);
		in.next();
	}
}

The compilation can pass, but an exception is thrown after running and inputting the first data.

problem:

Exception in thread "main" java.util.NoSuchElementException
	at java.util.Scanner.throwFor(Unknown Source)
	at java.util.Scanner.next(Unknown Source)
	at com.tulun.classandobject.Test_Scanner.main(Test_Scanner.java:12)

the reason

Source code:

  /**
     * Closes this scanner.
     *
     * <p> If this scanner has not yet been closed then if its underlying
     * {@linkplain java.lang.Readable readable} also implements the {@link
     * java.io.Closeable} interface then the readable's <tt>close</tt> method
     * will be invoked.  If this scanner is already closed then invoking this
     * method will have no effect.
     *
     * <p>Attempting to perform search operations after a scanner has
     * been closed will result in an {@link IllegalStateException}.
     *
     */
    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;
    }

 Understand this: The created multiple Scanner objects share the same input stream (System.in). When the close() method is called, the input stream of System.in is closed. Therefore, for the in created for the second time, System.in has been closed, and the object cannot be created normally, resulting in java.util.NoSuchElementException.

solution:

Call close() at the end of the code to close the input stream.

Reference

https://www.cnblogs.com/qingyibusi/p/5812725.html
https://blog.csdn.net/fashion_man/article/details/82973029

Guess you like

Origin blog.csdn.net/qq_41571459/article/details/113532017