![](/img/trans.png)
[英]How to loop a prompt for a user to re-enter a number if they input a number outside of the parameters
[英]How to prompt the user to re-enter a value if a mistake was made and How to give an option to keep on checking pay rates or to exit the program.?
Java应用程序输入一个销售人员的商品及其上周的相应销售额,然后计算并显示该销售人员的收入。
for (int item =1; item < 5; item++){
System.out.printf("\nHow many of item %d have you sold: ", item);
count=input.nextInt();
if (item == 1)
sales = item1* count;
if (item == 2)
sales2 = item2 * count;
if (item == 3)
sales3 = item3 * count;
if (item == 4)
sales4 = item4 * count;
}
您可以一直循环,直到用户输入正确的数量。您可以使用用户输入的默认值退出循环。 根据我的理解:
while(true)
{
System.out.printf("\nHow many of item %d have you sold: (Enter -999 to exit)", item);
count=input.nextInt();
if(count== -999) //Or some default value of your choice, exit the loop
{
System.out.printf("Program terminated");
break;
}
for (int item =1; item < 5; item++)
{
if (item == 1)
sales = item1* count;
if (item == 2)
sales2 = item2 * count;
if (item == 3)
sales3 = item3 * count;
if (item == 4)
sales4 = item4 * count;
}
}
使用while循环更好,因此您可以执行以下操作:
While(true){
System.out.printf("\nHow many of item %d have you sold: ", item);
count =input.nextInt();
if(certain condition is reached)
break;
if (item == 1)
sales = item1* count;
else if (item == 2)
sales2 = item2 * count;
else if (item == 3)
sales3 = item3 * count;
else if (item == 4)
sales4 = item4 * count;
}
然后,你可以添加一个break
中的控制的一个地方声明if
内环路条件或其他地方退出循环。 例如,您可以使用计数器来计算它们输入值的次数,然后在达到该值时退出循环。 这完全取决于您和您的要求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.