0

I cannot get out of while loop.

I do not why sc.hasNextInt() does not return false after last read number.

Should I use another method or is there a mistake in my code?

public static void main(String[] args) {

        // Creating an array by user keyboard input
        Scanner sc = new Scanner(System.in);

        System.out.println("Length of array: ");
        int[] numbers = new int[sc.nextInt()];

        System.out.printf("Type in integer elements of array ", numbers.length);
        int index = 0;
        **while ( sc.hasNextInt()) {**
            numbers[index++] = sc.nextInt();


        }
        // created method for printing arrays
        printArray(numbers);
        sc.close();


}
Petar Bivolarski
  • 1,599
  • 10
  • 19
Miki
  • 31
  • 7

2 Answers2

0

When you are receiving your input from the console, the Scanner hasNextInt() method placed inside a while loop condition will continue to read (meaning the loop will continue), until one of the following happens:

  • You submit a non-numeric symbol (e.g. a letter).
  • You submit a so-called "end of file" character, which is a special symbol telling the Scanner to stop reading.

Thus, in your case you cannot have the hasNextInt() inside your while loop condition - I am showing a solution below with a counter variable that you can use.

However, the hasNextInt() method inside a while loop has its practical usage for when reading from a different source than the console - e.g. from a String or a file. Inspired from the examples here, suppose we have:

String s = "Hello World! 3 + 3.0 = 6 ";

We can then pass the string s as an input source to the Scanner (notice that we are not passing System.in to the constructor):

Scanner scanner = new Scanner(s);

Then loop until hasNext(), which checks if there is another token of any type in the input. Inside the loop, perform a check if this token is an int using hasNextInt() and print it, otherwise pass the token to the next one using next():

while (scanner.hasNext()) {
    if (scanner.hasNextInt()) {
        System.out.println("Found int value: " + scanner.next());
    } else {
        scanner.next();
    }
}

Result:

Found int value: 3
Found int value: 6

In the example above, we cannot use hasNextInt() in the while loop condition itself, because the method returns false on the first non-int character that it finds (so the loop closes immediately, as our String begins with a letter).

However, we could use while (hasNextInt()) to read the list of numbers from a file.

Now, the solution to your problem would be to place the index variable inside the while loop condition:

while (index < numbers.length) {
    numbers[index++] = sc.nextInt();
}

Or for clarity`s sake, make a specific counter variable:

int index = 0;
int counter = 0;
while (counter < numbers.length) {
       numbers[index++] = sc.nextInt();
       counter++;
}
Petar Bivolarski
  • 1,599
  • 10
  • 19
  • Thank you very much for your answer. But is possible to write it hasNextInt() method? – Miki Mar 20 '20 at 18:08
  • If you write it with hasNextInt() method and you are receiving input from the console, the Scanner will loop until you pass a non-int character (a letter for example) or a special symbol that marks the end of the program. But in your case, this is not what you want. A practical example for using hasNextInt() in the loop condition is when you are not reading input from the console, but from a String - the Scanner will then parse the String until it has a next int and stop at the end - see here: https://www.tutorialspoint.com/java/util/scanner_hasnextint.htm – Petar Bivolarski Mar 20 '20 at 18:30
  • Exactly what I was looking for. Thank you. – Miki Mar 20 '20 at 18:33
  • @PetarBivolarski great explanation; I would put that in the main respond as to why `hasNextInt()` wouldn't work. – Kousha Mar 20 '20 at 20:02
  • Thanks a lot Kousha, I updated my answer with an elaborate explanation (in the process I noticed a small mistake in my comment above too, as hasNext() parses a String to the end, not hasNextInt() - it stops / returns false on the first non-int character it finds). – Petar Bivolarski Mar 20 '20 at 21:33
0

Do the following:

Use the input length as the end of the loop.

        // Creating an array by user keyboard input
        Scanner sc = new Scanner(System.in);

        System.out.println("Length of array: ");

        int len = sc.nextInt();
        int[] numbers = new int[len]; // use len here

        System.out.printf("Type in integer elements of array ", numbers.length);
        int index = 0;
        for (index = 0; index < len; index++) { // and use len here
            numbers[index] = sc.nextInt();
        }
        // created method for printing arrays
        printArray(numbers);
        sc.close();

And don't close the scanner.

WJS
  • 36,363
  • 4
  • 24
  • 39
  • 1
    Why should scanner be left open? – Miki Mar 22 '20 at 10:12
  • 1
    In general it's a bad habit to get into. Try this. close the Scanner. Then in the same program, try creating a new one using `System.in`. The problem is that when you close the scanner it also closes the underlying input stream if one exists. – WJS Mar 22 '20 at 12:25