2016-09-20 89 views
-3

我是Java初學者,請耐心等待,不要因缺乏研究而判斷。在這裏我出多次循環的無效輸入後重新提示用戶

這個程序是基本的計算程序。它爲用戶設計計算項目的總成本。

我的程序調試正常,但問題是當用戶鍵入無效的條目。 一旦用戶鍵入無效的條目,for循環剛結束後Please, enter the amount!

我希望程序保持for循環,直到用戶鍵入一個有效的條目。

import java.util.Scanner; 

public class icalculator { 

    public static void main(String[] args) { 
     Scanner Keyboard = new Scanner(System.in); 
     double cost, percentage; 
     int years; 


     System.out.println("What the estimate cost of the project?"); 
     cost = Keyboard.nextDouble(); 

     if (cost <= 0) { 
      System.out.println("Please, enter the amount!"); 
     } else if(cost > 0) { 

      System.out.println("What the estimate percentage cost of the project? "); 
      percentage = Keyboard.nextDouble(); 

      if (percentage <= 0) { 
       System.out.println("Please, enter the amount!"); 
      } else if(percentage > 0) { 

       System.out.println("How long it will take to complete the project? \n" 
         + "Please, enter whole numbers."); 
       years = Keyboard.nextInt(); 

       if (years <= 0) { 
        System.out.println("Please, enter the amount!"); 
       } else if (years > 0) { 

這部分是計算區域:

double c = cost; 
         double p = percentage; 
         int y = years; 

         for (int i = 1; i <= 1; i++) { 
          c = Math.round(((p/100) * c) + y); 
          System.out.println("At " + percentage + "% rate, the cost of the project will be $" 
            + c + " which take " + years + " years to be complete"); 
         } 


        } 
       } 
      } 
     } 

我在想,如果do while循環會更好,但我沒有試圖讓更多的complaicated那麼它是什麼節目。

+0

目前尚不清楚你描述/觀察的實際問題是什麼。你能具體嗎? – David

+0

@David當我運行該程序時,如果用戶鍵入無效的條目,程序將回答「請輸入數量!」,然後程序結束。我希望程序繼續執行for循環,直到用戶輸入有效的條目。 – krillavilla

回答

0

我不確定這個概念是否存在更多的「官方」術語,但是聽起來像任何給定的用戶輸入都希望有一個「輸入循環」,直到提供了有效的值。 (而目前的代碼沒有辦法「回到提示符」,並且當if檢查有效值不被滿足時,邏輯簡單地結束)。

對於每個輸入,它可能看起來像這樣:

double cost = 0; 
while (cost <= 0) { 
    System.out.println("What the estimate cost of the project?"); 
    cost = Keyboard.nextDouble(); 

    if (cost <= 0) { 
     System.out.println("Please, enter the amount!"); 
    } 
} 

毫無疑問,有多種方式來構造它,但概念是相同的。將該變量聲明爲初始(業務無效)值,重複提示用戶,直到該值爲業務有效,因此在循環之後,您知道您具有有效值。

通過將此過程封裝到自己的方法中,您可以進一步指導您的學習/練習,這種方法會從用戶返回所需的值。您的main()方法會調用另一種方法來獲取值。在爲每個輸入封裝後,注意相似之處,看看是否可以將封裝操作重構爲單個方法而不是單獨的每個輸入方法。 (請記住清楚而恰當地命名事物,如果意義在重構後發生變化,請更改名稱)

最終,理想的結構是遠離這些嵌套括號(if s中的if s等)推向右邊),而是有一組簡單的有名的方法調用,它們本身描述正在執行的整體操作。