![](/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.