Today, when using the scanner class to obtain data from the console, a Java. Util. NoSuchElementException exception was reported
Here is the problem code
public static void init(LinkList l){
for(int i=0;i<3;i++){
System.out.println("Please enter the "+i+" value");
Scanner temp=new Scanner(System.in);
int len=temp.nextInt();
l.addNode(len);
temp.close();
}
}
When you want to input the second data, you will report an error. This is abnormal information
Please enter the 0th value
2
Please enter the 1st value
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at com.zji.List.LinkList.init(LinkList.java:33)
at com.zji.List.LinkList.main(LinkList.java:60)
This is because temp. Close() is closed in the for loop. Just write temp. Close() outside the for loop
At first, I thought I’d cycle through a new scanner and turn it off. Can’t I turn it on again?No! This is because your scanner. Close will call the system. In. Close method to close the system. In. After you, new scanner will not help you open the system. In stream, so an error is reported
The following is the source code of the close method, which you can refer to
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;
}
Similar Posts:
- Error log: resource leak: ‘xxx’ is never closed (precautions for scanner class)
- Solution to the problem of Java program “resource leak: ‘SC’ is never closed” in vscode
- JAVA: scanner Read File encoding Error noSuchElementException
- Java – Stream has already been operated upon or closed
- Project startup error: communications link failure
- [Solved] Flume startup error: org.apache.flume.FlumeException: Failed to set up server socket
- Java error: No enclosing instance of type E is accessible. Must qualify the allocation with an enclosing
- How to Solve TestNG Frame Warning:Cannot find class in classpath: NewTest
- [Solved] ava.io.IOException: HADOOP_HOME or hadoop.home.dir are not set
- [Solved] java.util.zip.ZipException: invalid LOC header (bad signature)