1

I have a piece of code which should read input word by word and add the length of the word to an ArrayList recursively (for a school exercise).

I wrote this method:

ArrayList<Integer> wordLengths = new ArrayList<Integer>();
Scanner scanner = new Scanner(System.in);
// ...
private void readWords() {
    // read a word, if there are more words, read the next word
    this.wordLengths.add(this.scanner.next().length());

    if (this.scanner.hasNext()) {
        readWords();
    }
}

When I call this method, it keeps asking for new words. It won't stop the (recursive) loop. Why is this happening? this.scanner.hasNext() should only be true when there's a next word in the input so it should stop when there is no other word.

Jochem Kuijpers
  • 1,770
  • 3
  • 17
  • 34

2 Answers2

3

System.in is an input stream. It is never closed, so it will always return true for #hasNext()

codethulhu
  • 3,976
  • 2
  • 21
  • 15
  • Thanks. I'll keep that in mind next time! I'll select your answer when I'm able to unless a better one shows up. – Jochem Kuijpers Sep 30 '13 at 19:07
  • 2
    Not quite true. `hasNext()` can return `false` if an end-of-file condition on the input is reached. I just tried it on a Windows system and I got the program to work (in a Command Prompt window) by typing control-Z and then . Redirecting standard input works too. This may be platform-dependent, and I don't know whether Eclipse's console input would be able to trigger an end-of-file condition. – ajb Sep 30 '13 at 19:13
0

Use Ctrl+Z(+Enter) in Windows or Ctrl+D in Unix to send EOF and terminate input stream

  • Well, I haven't used Eclipse for years but I assume that you can just do it in console view (place your cursor in console view, press Ctrl+Z and then Enter) – Mateusz Antkiewicz Sep 30 '13 at 19:26