简体   繁体   中英

Do-While loop and hasNextInt()

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

因为hasNextInt阻塞,直到控制台上有一个int ,因此不会进入循环的下一次迭代。

Welcome. See answer in comments. Hope it is clear :-)

do {
        System.out.print("Enter a number:\t");  // Prints "Enter a number: "
        v[index] = console.nextInt(); // accepts input "1"
        index++; // increments
    } while(console.hasNextInt()); // waits for input at which point you enter "2"

Ok Let's make it clearer.

The do while loop, executes the do block before it evaluates the while condition. And then if the while condition evaluates to true, it executes the do block again and repeats until the while condition evaluates to false. .

Both console.nextInt and console.hasNextInt read input from the console. So as part of the do block, the "Enter a number:\\t" has been printed out, The first nextInt() call has accepted the input "1", which is then followed by the increment, followed by evaluation of the while condition - the console.hasNextInt(), which again waits for input and accepts "2". This explains why the "Enter a number:\\t" was not printed before the User Input of "2"

Of course because the value 2 has been entered, the while condition evaluates to true and again the do block is executed and goes on.

Perhaps you need the while loop. This, by contrast, executes the code block only if and as long as the while condition evaluates to true

System.out.print("Enter a number:\t");
while(console.hasNextInt()){
        v[index] = console.nextInt(); 
        index++; // increments
        System.out.print("Enter a number:\t");  
    } 

Think of exiting the loop when you reached the enough size of the array. something like

   do {
            System.out.print("Enter a number:\t");
            v[index] = console.nextInt();
            index++;
        } while(index<10); // if you want the user to enter 10 numbers. 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM