gpt4 book ai didi

java - 尝试将多个 double 添加到 java 中的数组

转载 作者:行者123 更新时间:2023-11-29 04:56:19 27 4
gpt4 key购买 nike

我正在尝试将购买列表添加到数组,然后能够根据数组中的 double 执行一些计算。我在尝试将购买添加到双阵列时遇到问题这是我拥有的:

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[]。因此,您需要创建一个新数组,其大小为 purchases + pur,并将 pur 的每个元素复制到 purchases 的末尾。

请尝试以下代码:

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];
}
}

关于java - 尝试将多个 double 添加到 java 中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33643896/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com