【发布时间】:2016-10-14 16:02:13
【问题描述】:
所以我想将一个新项目推送到数组的末尾(数字 1-9)。一个朋友告诉我,我写的代码是正确的,但是当我在eclipse上运行它时,什么都没有发生。我需要做什么?我应该只在主块下打印数组吗?谢谢。
public static void main(String[] args) {
long[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
}
public static long[] push(long[] array, long item) {
// Add one item to an array
long cellsToAdd = 1;
long[] array2 = new long[array.length + 1];
// copy each item in array2 -> array3
for (int i = 0; i < array.length; i++) {
array[i] = array2[i];
}
array2[array2.length - 1] = item;
System.out.println("Array: ");
// Print the array to the console
for (long p : array2) {
System.out.println(p);
}
return array2;
}
【问题讨论】:
-
你没有调用函数
-
你应该从 main 方法调用
push。 -
还要注意,Java 数组具有固定长度。你不能把任何东西推到最后。相反,您提供的代码会创建一个新的、更长的数组,其中包含所需的内容。这本身并没有什么问题,但重要的是要理解这与你所问的问题之间的区别。