簡體   English   中英

如果發生錯誤,如何提示用戶重新輸入值,以及如何提供繼續檢查工資率或退出程序的選項?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM