Home > Software design >  While loop printing error statement after while(true) is broken
While loop printing error statement after while(true) is broken

Time:03-05

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

CodePudding user response:

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

CodePudding user response:

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