0

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());
    numCheck(guessedNum);
}
timeEnd = System.currentTimeMillis();
input.close();
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());
    input.close();
    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.

facundop
  • 482
  • 6
  • 28
  • 2
    Probably due to the same underlying cause as this other [NoSuchElementException](http://stackoverflow.com/questions/13063047/nosuchelementexception) related question. Closing the scanner will also close `System.in`, so if you try `new Scanner(System.in)` *again* after you closed a similar scanner earlier, it won't read anything. – Dennis Meng Jan 29 '14 at 04:59
  • Thank you for your answer but I don't understand the behaviour. If I open it again with Scanner input = new Scanner(System.in);, shouldn't it read again just as it did before? – facundop Jan 29 '14 at 05:55
  • No, because `System.in` is still closed. Creating that second scanner won't reopen it. – Dennis Meng Jan 29 '14 at 05:55

1 Answers1

2

Your closing the Scanner in this line:

input.close();

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

Ant's
  • 13,545
  • 27
  • 98
  • 148