0

Double scanners

Why is this not working? It only prints out the first input import java.util.Scanner; class MyClass { public static void main(String[ ] args) { Scanner myVar = new Scanner(System.in); System.out.println(myVar.nextInt()); Scanner myInt = new Scanner(System.in); System.out.println(myInt.nextInt()); } } Response: 123 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 MyClass.main(MyClass.java:8)

18th Jun 2018, 12:26 AM
Mohammad Abdul Salam
3 Antworten
+ 6
myVar.nextInt(); myVar.nextInt(); There is no need of creating two instances of the Scanner. You can take any number of inputs* with only ONE instance! * This depends on its scope. { } is a scope block. Anything declared INSIDE it, cannot be used anywhere OUTSIDE.
18th Jun 2018, 1:21 AM
Dev
Dev - avatar
+ 1
You need to type in two user inputs For example: 123 123 Since you created two scanners, you need to type in a user input twice
18th Jun 2018, 2:22 AM
Paul Yan
Paul Yan - avatar