Java 构造函数获取数组作为参数;如何使用它

Java 构造函数获取数组作为参数;如何使用它,java,arrays,constructor,Java,Arrays,Constructor,嗨,伙计们 所以我的问题是我有以下构造函数: int tuple[]; NaturalNumberTuple nnt; public NaturalNumberTuple(int[] numbers) { int[] tuple = new int[numbers.length]; for(int i : numbers){ tuple[i] = numbers[i]; } // TODO implement constructor // t

嗨,伙计们

所以我的问题是我有以下构造函数:

int tuple[];
NaturalNumberTuple nnt;
public NaturalNumberTuple(int[] numbers) {
    int[] tuple = new int[numbers.length];
    for(int i : numbers){
        tuple[i] = numbers[i];
    }
    // TODO implement constructor
   // throw new UnsupportedOperationException("Constructor not yet implemented");
}
现在,我正在尝试执行以下任务:

/**
 * Inserts the specified {@code number} at the end of this tuple. If {@code number} is smaller or equal to 0, this
 * method has no effect.
 * 
 * @param number
 *            the number to be inserted
 * @return the tuple resulting from inserting the specified {@code number}. If {@code number} is smaller or equal to
 *         0, this tuple is returned without any modifications.
 */
public NaturalNumberTuple insert(int number) {
    int placeholderTuple[] = new int[tuple.length+1];
    for(int i : tuple){
        placeholderTuple[i] = tuple[i];
        if(number > 0){
            placeholderTuple[placeholderTuple.length-1] = number;
        }
    } 
    return nnt.NaturalNumberTuple(placeholderTuple[]);
}
错误出现在我的最后一行(返回nnt…) 语法错误,请插入“.class”以完成ArgumentList 和 对于类型NaturalNumberTuple,未定义方法NaturalNumberTuple(类)

所以我想我为什么要实现另一个类?我已经得到了一个名为NaturalNumber的元组,所以我真的不知道为什么会出现这个错误。。此外,我还有一个问题。正如您所看到的,我在这里使用数组,如果我(例如)想要构造一个新的元组,我将使用我的构造函数,但是我如何将数组传递给它呢? 你可以在最后一排查我的第一次尝试

对不起,如果这些代码样本格式不好,对不起,我的英语不好

谢谢你

已解决:

首先谢谢你们! 我必须做到以下几点:(针对其他可能有类似问题的人)

首先,在我的构造函数中,我必须替换该行

int[] tuple = new int[numbers.length];

因为我已经定义了数组元组

第二:

return nnt.NaturalNumberTuple(placeholderTuple[]);
return nnt.NaturalNumberTuple(placeholderTuple[]);


占位符元组
被定义为数组,因此在将其作为参数传递给方法时,无需添加额外的括号
[]

最后一行应该是:
返回新的自然数元组(占位符元组)

两个问题:

  • change
    返回nnt.NaturalNumberTuple(占位符tuple[])
    to
    返回新的自然数元组(占位符元组)
您需要使用新运算符调用构造函数,但不使用“[]”

  • 更改此行
    int[]tuple=newint[numbers.length]
    元组=新整数[numbers.length]

您正在重新定义元组,当您尝试从其他实例访问该元组时,该元组将留下空数组。

除了cello的要点之外,您正在搞乱构造函数的工作方式。只有在使用“new”创建新实例时,才会调用构造函数

所以,替换那个


@Makoto他们不是,只是意图不好……不要用
[已解决]
标记你的问题。接受一个答案。但是一切都帮了我:/lol选择哪一个
return new NaturalNumberTuple(placeholderTuple);
return nnt.NaturalNumberTuple(placeholderTuple[]);
return new NaturalNumberTuple(placeholderTuple);