1

I need the user to enter a list of integers in a single line, so I wrote this:

public static Integer[] readIntegers()
{
    Scanner input = new Scanner(System.in);
    List<Integer> list = new ArrayList<Integer>();
    do list.add(input.nextInt());
    while(input.hasNextInt());
    return list.toArray(new Integer[list.size()]);
}

but it keeps looping forever! Doesn't hasNextInt() supposed to return false if there are no digits on the scanner? How can I fix the previous method? Or should I use nextLine() instead and spilt the String?

Charles
  • 50,943
  • 13
  • 104
  • 142
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417

3 Answers3

3

System.in does not "end" because you press enter. If you want to do it this way, you could probably check for '\n' in the while expression.

Generally, I would prefer to do it in another way:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();  // line == null indicates end of input.

or using java.io.Console.

Also, if you use do/while instead of while you might get problems if the input is empty.

Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
tim
  • 1,999
  • 17
  • 32
  • Nice answer. Do you need to specify an encoding for `InputStreamReader`? I assume `System.in` already has an encoding associated with it because it's a `PrintStream`, but `InputStreamReader` probably won't pick up on that. – Mike Samuel Jan 13 '12 at 16:49
1

I Believe you just didn't put EOF to your stdin, so your program is waiting for next input..

To feed EOF, use ctrl+z on windows or ctrl+d on linux.

amit
  • 175,853
  • 27
  • 231
  • 333
  • @Eng.Fouad: You are feeding input to your method from command line. The command line is just like a long file, and it keeps reading until it encounters EOF. Just feed [manually, the same way you feed numbers...] EOF to your stdin. – amit Jan 13 '12 at 15:50
  • Well, I got this exception when I tried ctrl+z on eclipse (windows) `java.util.NoSuchElementException` – Eng.Fouad Jan 13 '12 at 15:50
  • 1
    Scanner throws "NoSuchElementException - if input is exhausted" see http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html#nextInt%28%29 – fasseg Jan 13 '12 at 15:52
  • @Eng.Fouad Your code assumes there is always at least one integer. If you uses a while loop, it would allow for no values. – Peter Lawrey Jan 13 '12 at 15:53
1

It would be better if you just read a single line and put its contents in a Scanner. This way, the user wouldn't have to put in an EOF, but rather just press enter.

Also, you want a while loop instead of a do...while, because it might be that no numbers are entered. Since the do...while first checks the condition after one iteration, your code attempts to read at least one integer, even if there aren't any.

Vlad
  • 18,195
  • 4
  • 41
  • 71