I know I’m going out on a limb here, but I just can’t seem to understand why can’t we just create an instance of the Scanner class twice. I’ll add an example just in case.
import java.util.Scanner;
public class Nope
{
public static void main(String[] args)
{
System.out.println("What's your name?");
Scanner scanner = new Scanner(System.in);
String name = scanner.nextLine();
System.out.println("Welcome " + name + "!");
scanner.close();
// Now
System.out.println("where you do live?");
Scanner sc = new Scanner(System.in);
String country = sc.nextLine();
System.out.println("That's a lovely place");
sc.close();
}
}
And I get a runtime error which looks something like this
What's your name?
Kate
Welcome Kate!
Exception in thread "main" where you do live?
java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
at Nope.main(Nope.java:17)
I know it doesn’t make sense to create a new object again of the same class, encouraging redundancy. But I just think it will clear my mind if I know why, don’t you think so too?
What does the machine mean by ‘java.util.NoSuchElementException: No line found’ and people are saying Scanner ain’t cloneable.
PS: I intentionally closed my first scanner and created a new object just to understand the issue.
Advertisement
Answer
There are actually two separate things going on here.
You should create one
Scannerper input source. For example, oneScannerfor each distinct input file, one forSystem.in, one for each distinct socket input stream.The reason is (as Chrylis points out) is that various methods of
Scannerread ahead on the scanner’s input source. When the characters are not consumed by the operation, they are not put back into the input source. Rather they are buffered by theScanneritself, and kept for the nextScanneroperation to use. So if you have twoScannerinstances trying to read from the same input source, one may “steal” input intended for the other.This is the real reason why opening multiple
Scannerobjects onSystem.inis bad. Not the “redundancy” argument that you proposed. There is nothing fundamentally wrong with a bit of redundancy … especially if it simplifies the application. But scanners competing for input may result in unexpected behavior / bugs.The second problem is that when you
close()aScannerthat also closes the input source.In your case that means that you are closing
System.in. And then you are creating a secondScannerto read from the (now closed)System.in.When you attempt to us a
Scannerto read from a closedSystem.in, that leads to aNoSuchElementException.
So if you hadn’t called close() on the first Scanner, your code might have worked, but that would depend on the sequence of operations you made on the first Scanner.
People are saying
Scannerain’t cloneable.
They are correct.