简体   繁体   English

while(true) 中断后 while 循环打印错误语句

[英]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.在下面的代码中,我试图提示用户输入一个数字,如果小于 1,则要求输入另一个正数。

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.然后在循环内将打印输出移至nextInt()调用上方。

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:您可以添加一个break语句,它退出循环,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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