'While loop printing error statement after while(true) is broken

In the following code, I am trying to prompt a user to enter a number, and if it is less than 1, ask for another positive number.

It seems to be working until the positive number is input but the program will print a final error message after the positive number is given.

How do I stop this error message from being printed after the positive number is input?

System.out.println("Enter number");
int x = 0;

while (x < 1)
{  
   x = input.nextInt();
   System.out.println("ERROR - number must be positive! Enter another");
}


Solution 1:[1]

Read the initial number unconditionally before the loop. Then inside the loop move the printout above the nextInt() call.

System.out.println("Enter number");
int x = input.nextInt();

while (x < 1)
{  
   System.out.println("ERROR - number must be positive! Enter another");
   x = input.nextInt();
}

Solution 2:[2]

You can add a break statement, which exits a loop, like so:

while (x < 1)
{  
  x = input.nextInt();

  if (x >= 1) 
  {
     System.out.println("Mmm, delicious positive numbers");
     break;
  }

  System.out.println("ERROR - number must be positive! Enter another");
}

Or alternatively:

while (x < 1)
{  
  x = input.nextInt();

  if (x < 1)
  {
     System.out.println("ERROR - number must be positive! Enter another");
  }
  else
  {
     System.out.println("Congratulations, you can read directions!");
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 John Kugelman
Solution 2 automaton