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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…