如何初始化本地数组中的值?

时间:2018-02-06 14:50:56

标签: 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 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; 

        } 
    } 

1 个答案:

答案 0 :(得分:1)

首先,您需要定义一个数组并使用给定的值对其进行初始化。这可以直接在变量的声明上完成。然后你需要将引用传递给反向方法。

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;

    }
}

您可以在此处找到有关如何初始化阵列的更多信息: http://www.baeldung.com/java-initialize-array