Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do-While loop and hasNextInt()

Tags:

java

I know this might sound like a really stupid question but I cannot understand where is my mistake.

Why on the second iteration of the loop, it does not print 'Enter a number:'?

import java.util.Scanner;

public class Main{
    public static void main(String[] args){
        Scanner console = new Scanner(System.in);
        int[] v = new int[10];
        int index = 0;
        do {
            System.out.print("Enter a number:\t");
            v[index] = console.nextInt();
            index++;
        } while(console.hasNextInt());

        for (int i = 0; i < index; i++){
            System.out.print(v[i] + "\t");
        }
        System.out.println("\n" + index);
    }
}

And this is the output:

Enter a number: 1
2
Enter a number: 3
Enter a number: 4
Enter a number: 5
Enter a number: ^D
1       2       3       4       5
5
like image 852
Aman Avatar asked Jun 04 '26 18:06

Aman


1 Answers

Because hasNextInt blocks until there is an int on the console, therefore not entering the next iteration of the loop.

like image 70
Federico klez Culloca Avatar answered Jun 07 '26 08:06

Federico klez Culloca



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!