facundop facundop - 1 year ago 159
Java Question

Java Scanner throws a NoSuchElementException

I'm learning Java, and by doing so, I've written a simple guessing game. Now I'm trying to improve it by adding additional features, but I'm stuck at trying to make it more "modular" i.e: using more methods vs a long main() method.

I have this:

while(!guessed) {
System.out.println("Guess a number between 1 and 1000.");
guessedNum = Integer.parseInt(input.nextLine());
timeEnd = System.currentTimeMillis();
System.out.println("Seconds to guess: " + (timeEnd - timeStart)/1000);

which works just fine, but if I try to make a separate method for "guess num" like this:

public static int guessNum() {
System.out.println("Escriba un numero entre 1 y 1000.");
Scanner input = new Scanner(System.in);
guessedNum = Integer.parseInt(input.nextLine());
return guessedNum;

it throws the following error:

Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at game.Guess.guessNum(Guess.java:40)
at game.Guess.start(Guess.java:28)
at game.Game.main(Game.java:21)

I've been trying to toy around using a delimiter and nextLine(), but it's always the same error. Also I've tried debugging it with eclipse, but when it goes to nextLine it jumps to a page which says Source not found.

Any clue? I can modify my question if needed.

Answer Source

Your closing the Scanner in this line:


which also closes the System.in. So next time you read from the same scanner, you will get this error.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download