简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM