前言:對於所有代碼感到抱歉,我知道大部分代碼對於這個問題都是多餘的。如果每個'交易'是一個對象,你如何存儲所有交易的總成本?
該類將描述(大小),成本和數量作爲參數,並返回創建對象的次數(transaction_number),爲所有創建的對象(total_quantity)指定的總數量和(應該)返回所有創建的對象的總成本。
public class SalesTransaction
{
private static int counter = 1;
public final int transaction_number;
private static int order_quantity = 0;
public final int total_quantity;
private static double temp_grand_total = 0;
public final double grand_total;
private String size;
private double cost;
private int quantity;
public SalesTransaction(String size, double cost, int quantity)
{
this.size = size;
this.cost = cost;
this.quantity = quantity;
this.transaction_number = counter++;
order_quantity += quantity;
this.total_quantity = order_quantity;
temp_grand_total += totalCostAfterTax(cost*quantity); // this is wrong!
this.grand_total = temp_grand_total;
}
public static double discountAmount(int quantity, double cost)
{
double discount_amount = 0;
if (quantity > 20)
{
discount_amount = cost * 0.10;
}
return discount_amount;
}
public static double totalCostBeforeTax(SalesTransaction temp)
{
double total_cost;
int quantity = temp.quantity;
double cost = temp.cost;
total_cost = quantity * cost;
double discount_amount = discountAmount(quantity, total_cost);
total_cost = total_cost - discount_amount;
return total_cost;
}
public static double totalCostAfterTax(double total_cost)
{
total_cost = total_cost * 1.15;
return total_cost;
}
public static void printStats(SalesTransaction temp)
{
System.out.println("Transaction Number: " + temp.transaction_number);
System.out.println("Size: " + temp.size);
System.out.println("Cost Per Table: "+ temp.cost);
System.out.println("Number of Tables: " + temp.quantity);
System.out.println("Total Tables So Far: " + temp.total_quantity);
double total_cost_before_tax = totalCostBeforeTax(temp);
double discount_amount = discountAmount(temp.quantity, total_cost_before_tax);
System.out.println("Discount: " + discount_amount);
double total_cost_after_tax = totalCostAfterTax(total_cost_before_tax);
temp.temp_grand_total = total_cost_after_tax;
System.out.println("Cost for this transaction: " + total_cost_after_tax);
System.out.println("Total cost: "+ temp.grand_total);
System.out.println();
}
}
而這僅僅是一個測試者類。
public class SalesTester
{
public static void main(String[] args)
{
SalesTransaction one = new SalesTransaction("Small", 10.0, 10);
one.printStats(one);
SalesTransaction two = new SalesTransaction("Medium", 20.0, 30);
two.printStats(two);
SalesTransaction three = new SalesTransaction("Large", 30.0, 40);
three.printStats(three);
}
}
問題是,我想不出如何存儲grand_total。我試圖以與存儲total_quantity相同的方式進行操作,但我可以看到爲什麼這種方式無法正常工作。
如何跟蹤所有事務(對象)的總數,然後我可以在控制檯上打印出來?
我假設在構造函數中有另一種表達方式,但我不知道如何找到這個例子。
我會將這些視爲訂單項,而交易將由多個訂單項組成。 –
交易的屬性與訂單項完全相同。這個練習的目的是練習我想象的某種簿記技能。 – Bruce