我剛剛開始在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);
}
}
在不同的說明,這不是一個好主意有一個單獨的方法,您必須調用才能使內部狀態正確。最好不要將'totalCost'作爲一個字段,但如果必須的話,應該從構造函數和任何setter調用'calculate'(方法名以小寫開頭)。 – chrylis 2015-02-23 06:17:57
你什麼時候調用'Calculations'?我最好有一個方法調用'getTotalCost'並返回計算結果而不是分配一個字段值 – MadProgrammer 2015-02-23 06:18:21
你的問題是什麼? – Jens 2015-02-23 06:18:26