我正在尝试将购买列表添加到数组中,然后能够基于数组中的双打执行一些计算。我在尝试向双阵列添加购买时遇到麻烦
这是我所拥有的:
public abstract class Customer {
protected String category;
protected String acctNumber;
protected String name;
protected double[] purchases;
protected static final double SALES_TAX_RATE = 0.08;
/**
*Reads in customer data.
*@param acctNumberIn customers account number.
*@param nameIn customers name.
*/
public Customer(String acctNumberIn, String nameIn) {
acctNumber = acctNumberIn;
name = nameIn;
purchases = new double[0];
}
在遇到问题时添加购买方式:
public void addPurchases(double ... pur) {
purchases = Arrays.copyOf(purchases, purchases.length + 1);
int a = purchases.length;
for (int i = 0; i < purchases.length; i++) {
purchases[a] = pur;
}
}
最佳答案
问题在于pur的类型为double []。因此,您将需要创建一个采购数量为pur的新数组,并将每个pur元素复制到采购结束。
请尝试以下代码:
public void addPurchases(double ... pur) {
int purchasesLength = purchases.length;
int combinedLength = pur.length + purchasesLength;
purchases = Arrays.copyOf(purchases, combinedLength);
for (int i = purchasesLength, j = 0; i < combinedLength; i++, j++) {
purchases[i] = pur[j];
}
}