Java 如何初始化本地数组中的值?
我在理解如何使用注释中列出的值初始化数组时遇到了一点困难。如何设置数组并继续使用下面的代码正确返回相应的输出 这个问题与复制链接不同,因为它询问如何在本地方法中初始化数组Java 如何初始化本地数组中的值?,java,arrays,sorting,local,Java,Arrays,Sorting,Local,我在理解如何使用注释中列出的值初始化数组时遇到了一点困难。如何设置数组并继续使用下面的代码正确返回相应的输出 这个问题与复制链接不同,因为它询问如何在本地方法中初始化数组 /*Write a method that reverses the sequence of elements in an array. For example, if you call the method with the array 1 4 9 16 9 7 4 9 11 then the a
/*Write a method that reverses the sequence of elements in an array. For example, if
you call the method with the array
1 4 9 16 9 7 4 9 11
then the array is changed to
11 9 4 7 9 16 9 4 1*/
public static void reverse(int[] array) {
for (int i = 0; i < array.length / 2; i++) {
int temp = array[i];
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = temp;
}
}
首先,您需要定义一个数组并用给定的值初始化它。这可以直接在变量声明上完成。然后需要将引用传递给reverse方法
public static void main(String[] args) {
int[] array = {1, 4, 9, 16, 9, 7, 4, 9, 11};
reverse(array);
Arrays
.stream(array)
.forEach(System.out::println);
}
private static void reverse(int[] array) {
for (int i = 0; i < array.length / 2; i++) {
int temp = array[i];
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = temp;
}
}
您可以在此处找到有关如何初始化数组的更多信息:
int[]数组={1,4,9,16,9,7,4,9,11};->反向耳环@nbokmans方法返回void,因此无法将其赋值给变量。@nbokmans赋值仍然存在;我的坏@Thomas-不知道我怎么搞砸了两次。顺便说一句,在我的评论的第一个代码块中有一个额外的括号,但是已经五分钟了,所以我不能更新我的评论。提示:你应该在发布问题之前做认真的研究。假设你作为新手提出的任何问题。。。我以前被问过。无数次。这是在你添加注释时完成的,所以它是不相关的。我似乎得到了一个重复的局部变量数组错误。你在单个代码范围内多次定义了一个名为array的变量。定义为:[TYPE][NAME]=[VALUE];使用搜索功能,查看是否有多个array=value;。我用我在机器上测试过的代码编辑了答案。