我想添加一个在数组中具有多个参数的新元素。我知道如何仅添加一个参数,但是我不知道添加更多的参数。
我的代码是:
private Calculate[] calculation;
public Element(int numElements) {
calculation = new Calculate[numElements];
}
public void addElement(Date elementDate, double price, ElementType type) {
int numElements = elements.length;
int i = 0;
if (i < numElements) {
Calculate[i] = calculation.elementDate;
Calculate[i] = calculation.price;
Calculate[i] = calculation.type;
i++;
}
}
答案 0 :(得分:3)
Calculate[i] = calculation.elementDate;
Calculate[i] = calculation.price;
Calculate[i] = calculation.type;
您不应分配给同一数组索引3次。您正在覆盖刚刚设置的内容。
尝试一下(Calculate
应该有一个构造函数):
Calculate[i] = new Calculate(elementDate, price, type);
您还维护着索引i
,但没有遍历任何内容。 i
只是从零到1递增,实际上并没有使用(除了几乎没有用的条件检查之外)。
我建议您阅读a beginners Java tutorial。您似乎缺少了很多基础知识,并且Stack Overflow并不是我们应该向您展示如何编写for循环的地方。它有充分的文档证明,并已在大量的教程中进行了演示。
答案 1 :(得分:0)
我假设Calculate是一个定义的类,否则使用构造函数
这段代码有两个问题:
您要更新数组,但要指定数组。 Calculate[]
是数组类型。数组为calculation
时的名称。另一件事是您尝试访问calculation.elementDate
等,但是由于这是一个数组,因此它没有字段elementDate。我假设您的Calculate类具有该字段。另外,您没有应用循环。因此,当前您的代码只会更新索引0上的数组。
我的代码:
public void addElement(Date elementDate, double price, ElementType type) {
for(int i = 0; i < elements.length; i++) { // for loop over all elements in your array
Calculate calculate = new Calculate(elementDate, price, type) // I assume this constructor is available to initialize the Calculate object
calculation[i] = calculate;
}
希望这会有所帮助。