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++;
}