2015-02-23 56 views
-2

我剛剛開始在Java課程中學習數組,所以我遇到了問題。我想用「成本」乘以「數量」,所以它會打印出總成本,但現在它打印出總成本0。這裏是驅動程序:如何在數組中添加兩個值?

import java.util.Scanner; 

public class Problem2 { 

public static void main(String[] args){ 

String purchase, date; 
double quantity, cost; 

Scanner myScanner = new Scanner (System.in); 

    System.out.println("How many different types of items are you purchasing?"); 
    int answer = myScanner.nextInt(); 
    myScanner.nextLine(); // pick up the enter key 

    Basket[] myBasket = new Basket[answer]; 
    for(int j = 0; j < answer; j++) { 

     System.out.println("Please enter the item you purchased."); 
     purchase = myScanner.nextLine(); 

     System.out.println("Please enter the date."); 
     date = myScanner.nextLine(); 

     System.out.println("Please enter the quantity."); 
     quantity = myScanner.nextFloat(); 

     System.out.println("Please enter the cost."); 
     cost = myScanner.nextFloat(); 
     myScanner.nextLine(); // pick up the enter key 

     myBasket[j] = new Basket(purchase, date, quantity, cost); 
    } 

    for (int i = 0; i< answer; i++) 
    { 
     System.out.println(myBasket[i]); 
    } 
} 
} 

這裏是車類:

import java.text.NumberFormat; 

public class Basket { 

    private String purchase, date; 
    private double quantity, cost, totalCost; 

    NumberFormat fmt = NumberFormat.getCurrencyInstance(); 

    public Basket(String purchase, String date, double quantity, double cost) 
    { 
     this.purchase = purchase; 
     this.date = date; 
     this.quantity = quantity; 
     this.cost = cost; 
    } 

    public void Calculations() 
    { 
     totalCost = cost * quantity; 
    } 

    public String toString() 
    { 
     return "Purchase: " + purchase 
     + "\nDate: " + date 
     +"\nQuantity: " + quantity 
     +"\nCost:" + fmt.format(totalCost); 
    } 
} 
+0

在不同的說明,這不是一個好主意有一個單獨的方法,您必須調用才能使內部狀態正確。最好不要將'totalCost'作爲一個字段,但如果必須的話,應該從構造函數和任何setter調用'calculate'(方法名以小寫開頭)。 – chrylis 2015-02-23 06:17:57

+4

你什麼時候調用'Calculations'?我最好有一個方法調用'getTotalCost'並返回計算結果而不是分配一個字段值 – MadProgrammer 2015-02-23 06:18:21

+0

你的問題是什麼? – Jens 2015-02-23 06:18:26

回答

0

添加Calculations();toString()

public String toString() 
{ 
    Calculations(); 
    return "Purchase: " + purchase 
    + "\nDate: " + date 
    +"\nQuantity: " + quantity 
    +"\nCost:" + fmt.format(totalCost); 
} 

或由於計算方法是公共的,你可以從主叫它方法與myBasket[j].Calculations();

af之三

myBasket[j] = new Basket(purchase, date, quantity, cost);

0

如果你想被填入TOTALCOST,你可以調用,當你創造一個像籃子的實例計算方法:

myBasket[j] = new Basket(purchase, date, quantity, cost); 
myBasket[j].Calculations(); 

現在,這將計算總成本,並將其保存在您可以稍後打印的姿態變量中。

0

在main(),添加以下代碼,最後一行後,

float total=0.0; 
for (int i = 0; i< answer; i++) 
{ 
    //System.out.println(myBasket[i]); 
     total+=myBasket[2]*myBasket[3]; 
} 
System.out.println("total cost:"+total); 
0

沒有被調用你的「計算」方法。 我想在構造函數的最後一行調用它。

順便說一句 - Java約定是在方法名稱的開頭小寫,而且最好用它做什麼它命名爲 - 「calculateTotalCost」例如