Assignment: Do while loop not working

Was assigned to write a program to read 3 numbers within the range of 0-3, and display it.

However the do while loop kind of does the opposite.

It should execute only if the input int is less than 4.
But it is acting the opposite way.
It will be kept in the loop till i key anything more than 4.

Is there something wrong with my understanding of do while loop?

Appreciate if any advise is given.

import java.util.Scanner;
class Main {
  public static void main(String[] args) 
  {
   Scanner input = new Scanner(System.in);
    int w;
    int[] numbers = new int[3];

   for(int i=0; i<3; i++)
    {
      do
      {
      System.out.print("Please key in non-negative number " +(i+1)+": ");
      numbers[i] = input.nextInt();
      w = numbers[i];

      }while(w < 4);

    
    } 
    System.out.println("The numbers are "+numbers[0]+" "+numbers[1]+" "+numbers[2]);
  }
}

Hello, @annchentay4462329411. Welcome to the forum.
If you want the loop to repeat until you get a valid int that is less than 4, you’ll want to reverse your logic. while (w > 3) will cause the loop to repeat (ie. keep asking for input) until you get a number no greater than 3. It appears from your description that you also want to eliminate numbers less than 0. You can add that condition to your while condition like so: while (w < 0 || w > 3); Now the loop will repeat until you get a number in the desired range. Happy coding!

3 Likes