2011-04-14 55 views
0

好的,所以我試圖創建一個「銷售稅計劃」,用戶可以在其中輸入項目並將其添加到數組中,名爲「costArray」。如何做到這一點,幾乎與一個字符串(因爲我需要costArray.length爲循環),但我有點失落。任何人都可以幫助我指出正確的方向,所以我可以:採取數組(數字雙)並應用乘數它(0.08銷售稅的百分比)和輸出總數(雙)?以下是我到目前爲止,你能告訴我,如果我關閉?謝謝!:Java對數組中的每個項目應用乘法

public class Input 
{ 
private Scanner keybd; 
private String item; 
private double cost; 
private String[] costArray; 
private String[] itemArray; 
/** 
    * Constructor for objects of class Scanner 
    */ 
public Input(int anyAmountofItems) 
{ 
    keybd = new Scanner(System.in); 
    costArray = new String[anyAmountofItems]; 
    itemArray = new String[anyAmountofItems]; 
} 
/** 
* Mutator method to set the item names and costs 
*/ 
public void setArray(){ 
    for(int index=0; index < itemArray.length; index++){ 
    System.out.println("Enter the item name: "); 
    itemArray[index] = keybd.next();} 
    for(int indexa=0; indexa < itemArray.length; indexa++){ 
     System.out.println(itemArray[indexa]); 
    } 
    for(int indexb=0; indexb < costArray.length; indexb++){ 
    System.out.println("Enter the item cost: "); 
    costArray[indexb] = keybd.next();} 
    for(int indexc=0; indexc < costArray.length; indexc++){ 
     System.out.println(costArray[indexc]); 
    } 
    } 
    /** 
    * Accessor method to return the items cost with tax 
    */ 
    public double getTax(){ 
     return costArray.length; 
    } 
    //   /** 
    //   * Mutator method to calculate tax on each item 
    //   */ 
    //   public void calculateTax(){ 
    //    for(int index=0; index < costArray.length; index++){ 
    //     System.out.println(0.08 * costArray[index]); 
    //    } 
    //   } 
    } 

回答

1

該號碼存儲在Stri NG,你必須「轉換」到一個實數(雙值)

做到這一點的方法如下所示:

String s = "-1.234"; 
double value = Double.parseDouble(s); 
0

數組是一個糟糕的主意,如果你不知道在他們將有的大小之前。爲什麼不使用ArrayList?如果你不知道它是正確的:你會真的需要它!

循環中的索引名稱與'i','n','p,q,r'或'x'一致,並且它們只存在於它們自己的循環中,因此您可以定義一個新的'i '在第二個循環中 - 不需要indexa,indexb,...。

對於學習來說,double可能已經足夠,但在現實世界中,您不應該對Money金額使用double,而應該使用BigDecimal。分數的比特表示導致其他令人驚訝的效果。

而掃描儀已經有像scanner.nextDouble()這樣的方法來讀取一個數字。

相關問題