Frank
Frank

Reputation: 753

first line of code in do...while loop skipped while entering the loop the second time - Java

here is my code

import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        int[] data = new int[10];
        int count = 0;

         do {
             System.out.print("Enter a number or ctrl + z when you are done: ");
             data[count] = input.nextInt();
         }
         while (input.hasNextDouble());
    }
}

output

Enter a number or ctrl + z when you are done: 2
4
Enter a number or ctrl + z when you are done: 6
Enter a number or ctrl + z when you are done: 8

My question is i don't know why the code jumps the System.out.print("Enter a number or ctrl + z when you are done: "); after do { when entering the loop the second time. This can be seen in second line of the output. Please what are my doing wrong?

I have searched for cases where my question might have already been answered but was only able to find solutions relating to code skipping nextLine()

Upvotes: 0

Views: 903

Answers (3)

Blasanka
Blasanka

Reputation: 22437

The reason is first time do block is executed and then check for condition in while.

About hasNextDouble() in orcale doc:

Returns true if the next token in this scanner's input can be interpreted as a double value using the nextDouble() method. The scanner does not advance past any input.

As a solution you can change the condition like below:

do {
     System.out.print("Enter a number or ctrl + z when you are done: ");
     data[count] = input.nextInt();
     count++;
 }
 while (count < 10);

Also:

If you are using input.nextInt();, better to check using hasNextInt().

Upvotes: 2

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79848

This happens because the first call to input.hasNextDouble() waits for a number to be entered before proceeding.

So the message in the second iteration of the loop won't appear until input.hasNextDouble() at the end of the first iteration of the loop has run - which of course fetches the second number.

You need to print the message before you call either hasNextDouble or hasNextInt.

Upvotes: 0

fringd
fringd

Reputation: 2528

ah your while loop is waiting to see if input hasNextDouble()

how can it know until your user has entered the next double or hit ctrl-z?

you'll have to do something Ugly like

System.out.print("Enter a number or ctrl + z when you are done: ");
do {
  data[count++] = input.nextInt();
  System.out.print("Enter a number or ctrl + z when you are done: ");
}
while (input.hasNextDouble());

note the count++ above as well i think it fixes another bug.

Upvotes: 1

Related Questions