I have started learning Java recently. I was learning to take user input using Scanner class when I Started getting an error. Here is the code:
Scanner userInput1 = new Scanner(System.in);
String name = userInput1.nextLine();
System.out.println("Hi "+ name);
userInput1.close();
Scanner userInput2 = new Scanner(System.in);
int age = userInput2.nextInt();
System.out.println(age);
I get the following error when I enter "Deadboy" as input:
Hi Deadboy
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at com.first.Main.main(Main.java:17)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Process finished with exit code 1
I am unable to enter the value for "age".
If, however, I comment the line "userInput1.close()", the code works.
What is the problem?
I am sorry if this question has been answered before. I found a similar question but I was not sure if its answers were the ones I was looking for.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…