There was a problem when using the Scanner class:
1 Exception in thread "main" java.util.NoSuchElementException2at Java.util.Scanner.throwFor (Unknown source)3at java.util.Scanner.next (Unknown source)
An exception was encountered while executing scanner.next (). The problem causes and solutions are given on Stack overflow.
Cause: When two and more than two scanner instances in a class, one instance of the scanner class executes the Scanner.close () method turns off other potential inputstream streams, causing the other scanner's scanners to fail to read the input stream.
Workaround: For the console program, only one instance of the scanner class is registered in the program run to read information from System.in.
Issue two: Skip the next scanner when using Scanner#nextint ().
Cause: When using Scanner#nextint (), Nextint () ends before encountering ' \ n ', but "\ n" is received by the next scanner, such as Scanner#nextline (), skipping Scanner#nextline () directly.
Workaround: Use Scanner#nextline () uniformly instead of all scan functions. It then enforces the type conversion.
1 // get The number as a single line 2 int // Convert the string to an int
Question One explanation:
You close the second Scanner
which closes the underlying InputStream
and therefore the first Scanner
can no longer read from the same and InputStream
a NoSuchElementException
results.
The Solution:for console apps, use a and Scanner
read from System.in
.
aside: As stated already, be aware this Scanner#nextInt
does not consume newline characters. Ensure that these is consumed before attempting to call nextLine
again by using Scanner#newLine()
.
Question two explanation:
nextInt()
The method leaves \n
the (end line) symbol nextLine()
and was picked up immediately by, skipping over the next input. W Hat you want to do are use nextLine()
for everything, and parse it later:
String nextIntString = keyboard.nextLine(); //get the number as a single lineint nextInt = Integer.parseInt(nextIntString); //convert the string to an int
This was by far the easiest-to avoid Problems--don ' t mix your "next" methods. Use with and then nextLine()
parse int
s or separate words afterwards.
Also, make sure the use of only one if your is only with Scanner
using one terminal for input. That could is another reason for the exception.
Last Note:compare a String
.equals()
with the function, not the ==
operator.
if (playAgain == "yes"); // Causes problemsif (playAgain.equals("yes")); // Works every time
Scanner class Throwfor (Unknown Source) and skip the next scanner analysis