scanner.nextInt() returns java.util.NoSuchElementException
This is my code, which is supposed to accept input from the user and set 2 int values. The exit function works correctly however when the input string is "5 2" for example, it sets x as 5 and throws the java.util.NoSuchElementException at the y =开发者_JAVA技巧 s2.nextInt(); line, even though there is a next int. In an example of nextInt() I saw, ints were seperated by a space and the scanner still picked up all the integers. Is mine missing something?
String exit = "-1";
Scanner s1 = new Scanner(System.in);
String input = s1.next();
Scanner s2 = new Scanner(input);
if (input.equals(exit))
Sequence.quit();
else {
x = s2.nextInt();
y = s2.nextInt();
}
If you print out your variable ìnput
, you will see that it contains only "5" - since s1.next()
wil stop at space.
Something like this:
String exit = "-1";
Scanner s1 = new Scanner(System.in);
int x = s1.nextInt();
if (x==-1)
Sequence.quit();
else {
y = s1.nextInt();
}
精彩评论