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
Because hasNextInt blocks until there is an int on the console, therefore not entering the next iteration of the loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With