Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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");
}

2 Answers

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();
}
like image 60
John Kugelman Avatar answered Nov 18 '25 21:11

John Kugelman


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!");
  }
}
like image 30
automaton Avatar answered Nov 18 '25 21:11

automaton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!