0

I have a while loop that's supposed to end when there are no more integers to be read. For some reason, it continues to keep checking (or at least I believe so) and won't return the print statement. My sample input would look like,

20 21 22 23

I've tried hasNextLine() before hasNextInt(), try/finally blocks and closing the scanner as well as reading through the forums.

If I phrased/formatted the question wrong or if there's another resource I haven't come across yet I would appreciate some feedback. I'm really just trying to learn.

public static void main(String[] args) {
    x = 0;
    in = new Scanner(System.in);

    while (in.hasNextInt()) {
        x = in.nextInt();
        reverse(x);
        beautiful(x, reverse(x), y);
    }

    printCount(count);
}
Aaron
  • 24,009
  • 2
  • 33
  • 57
  • 2
    When you read input from the standard input, the input never ends (the Scanner always waits for new input to be entered). You should require some special input to be entered in order to quit the loop. – Eran Nov 03 '16 at 10:38
  • 1
    Adding non integer values will break the loop, e.g `20 21 22 23 A` . – Arnaud Nov 03 '16 at 10:43

4 Answers4

0

in.hasNextInt() read data continuously. So you should use break; with appropriate condition after your requirement complete to stop this.

Chandana Kumara
  • 2,485
  • 1
  • 22
  • 25
0

After these lines

    while (in.hasNextInt()) {
        x = in.nextInt();

insert the line

        if (x == 0) break;

and the loop will stop after entering 0 - you may, of course, choose another number for stop, i. e. -1.

MarianD
  • 13,096
  • 12
  • 42
  • 54
0

I think there are many ways to solve this, but this one on my mind:

  1. create a second scanner and pass to it your first scanner input new Scanner(in.nextLine());
  2. create a while loop and go through until no numbers left. sc.hasNextInt()
Alex
  • 483
  • 1
  • 12
  • 23
0

Your input should be terminated in some manner. 1 2 3 4 and 1 2 3 4 5 are both valid inputs as scanner can't decide where to end on its own. It can be assumed that the number sequence is terminated by EOF character Ctrl-Z on windows and Ctrl-D on unix.

For more help on this look in to this link

Community
  • 1
  • 1
Zia
  • 1,001
  • 1
  • 13
  • 25