2012-01-26 35 views
2

我正在創建計算器來計算運費。代碼是這樣的:如何在Java中創建運費成本計算器

class ShippingCalc { 
    public static void main(String[] args) { 
     int weight = 30; 

     if (weight < 10) { 
      System.out.println("Shipping costs $1."); 
     } 
     else if (weight < 20) { 
      System.out.println("Shipping costs $2."); 
     } 
     else { 
      System.out.println("Shipping costs $3."); 
     } 
    } 
} 

這是偉大的,但我想創建一個計算器,可以根據已經設置的價值計算。例如,一些說:

if (weight < 250) { 
    // print("Shipping cost is $1); 
} else if (weight < 499) { 
    // print("Shipping cost is $2); 
} else if (weight < 749) { 
    // print...etc and it keeps going 

這將根據用戶的輸入,這就是爲什麼我不想已經有像上面的任何約束。是否有可能用Java製作這樣一個計算器,無論多少重量,它都會適當地計算運輸成本並給出答案。

如果是,那我該怎麼辦呢?

+3

是的,它可以通過使用簡單的數學和書寫代碼。你爲什麼不試一試,看看你想出了什麼。它總是**更好地嘗試解決事情,然後顯示你的努力,然後在這裏發佈你的任務。再次,它只不過是最基本的代數,我敢打賭你可以弄清楚,如果你把鉛筆放在紙上。 –

+0

它不是我的任務。我正在努力學習Java作爲一種愛好,因此標籤愛好。至於嘗試,我已經嘗試過,但我所能想到的只是有限的方式,將需要無限的代碼量。我不需要人爲我做,只是給我一個正確的方向推動。 – javacAA

+0

編輯,也許不是那麼容易,因爲你的數字沒有邏輯,除非它總是增加150美元。你將不得不爲這個'... etc'顯示更多的數字。請充分展示圖案。我沒有假設這是做作業,因爲我的建議對家庭作業或家庭作業(來自另一個最幸福的人)是有效的。 –

回答

4

首先,您需要一個公式或表格來計算運費。例如,「運費是每10磅體重一美元」。

然後,你把重量放在那個公式中。

System.out.println("Shipping cost is $" + (int)(weight/10)); 

如果您希望公式比較複雜,你可以做這樣的事情:

if (weight < threshold1) // price is first level 
// or, if you like, you can even do a calculation here 
else if (weight < threshold2) // price is second level 

這裏用戶可以定義threshold1threshold2變量的價值。

可以有這些級別的無限數:

// "thresholds" is a sorted array of the weights at which prices change 
int[] thresholds = new int[num_thresholds]; 
for (int checking = 0; checking < thresholds.length; checking++) { 
    if (weight < thresholds[checking]) // price is prices[checking] 
} 

歡迎計算機編程的奇妙世界!

+0

+1抱歉,無法登錄。感謝您的歡迎和答覆。 – javacAA

+0

@Borealid, 關於無限數量的關卡。我不太瞭解你的方法。你能否詳細說明一下。如果你必須設置[num_thresholds],它怎麼會是無界限的。如果體重沒有限制呢? – xiphias

1

如果成本權重符合公式,您應該使用它來計算成本(一個小代數從不會傷害任何人)。

如果成本分配權重是任意的,您可以使用權重作爲關鍵字和成本作爲值創建NavigableMap

然後,您可以使用NavigableMap<K, V>.lowerEntry(K)來查找低於給定重量的最高重量。

public static Integer findCost(Integer weight, 
     NavigableMap<Integer, Integer> costMap){ 
    Map.Entry<Integer, Integer> cost; 
    cost = costMap.lowerEntry(weight); 
    if(cost == null){ 
     cost = costMap.firstEntry(); 
    } 
    return cost.getValue(); 
} 

使用地圖的benifit是,如果你使用TreeMap爲您NavigableMap那麼你看看UPS將在平均爲O(log n)的實施。

+1

+1對不起,顯然不能。 – javacAA