小编典典

如何反向打印数组?

java

这是我的数组代码,我需要反向打印。

public class Array1D {
    public static void main(String[] args) {
        int[] array = new int[3];
        array[0] = 1;
        array[1] = 2;
        array[2] = 5;
        for (int i = 0; i < array.length; i++) { //loop
            System.out.print("array["+i+"]=");
            System.out.println(array[i] + "   ");
        }
        System.out.println("the last element in the matrix = " + array[array.length - 1]); // finding the last element in the array
        System.out.println("   ");
    }
}

阅读 297

收藏
2020-12-03

共1个答案

小编典典

只需反转for循环的方向即可。现在,它从0到长度开始计数,从长度到0开始计数

for (int i = array.length-1; i >= 0; i--)
2020-12-03