当while(true)被打破后,while循环会打印出错误语句。

3
在下面的代码中,我试图提示用户输入一个数字,如果它小于1,则要求输入另一个正数。 在正数被输入后,程序似乎可以工作,但会打印最终错误消息。 如何停止在输入正数后打印此错误消息?
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个回答

3
在循环前无条件读取初始数字。然后在循环内将打印输出移动到 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();
}

1

您可以添加一个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");
}

或者,另一种选择是:
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!");
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接