如何反转我的Int数组?

时间:2016-03-23 01:57:46

标签: java

public class ArrayFns {
    public static void main(String[] args)        
    {final int AR_SIZE = 10;
    banner();

    // create two arrays
    double[] dvals = { 3.14, 77.56, -7.0, 203.09 }; // initialize array
    double[] dvals2 = new double[8];
    int[] ivals = new int[AR_SIZE];

    System.out.print("\n\nivals                  -> ");
    printAr(ivals);
    System.out.print("reverseIt_print ivals  -> ");
    reverseIt_print(ivals);

    private static void reverseIt_print(int[] ivals)

    // print the series of int numbers in reverse order

    {
        int[] d = new int[ivals.length];
        for (int i = 0; i < ivals.length / 2; i++) {
            d[i] = ivals[i];
            ivals[i] = ivals[ivals.length - 1 - i];
            ivals[ivals.length - 1 - i] = d[i];

        }
        System.out.println(d);
    }

}

3 个答案:

答案 0 :(得分:1)

你可以向后循环..我在这里做的是声明一个原始类型int数组,然后向后循环..

 int[] normal = {1,2,3,4,5,6,7,8,9,10,11}    

     public static int[] reverseArray(int[] normalArray) {
            int[] reversedArray = new int[normalArray.length];
            for (int i = numbers.length-1, j = 0; i >= 0; i--, j++) {
                reversedArray[j] = numbers[i];
            }
            return reversedArray;
        }
     reverseArray(normal)

然后打印数据当然......

 private static void printReversedArray(int length, int[] array){
     for(int i=0; i<=length-1; i++){
      System.out.println(array[i])
     }         
  }

答案 1 :(得分:0)

如果您只想反向打印数组,请使用带有最大索引的for循环开始并向后工作。不需要新阵列。

for (int i = ivals.length - 1; i >= 0; i--) {
   System.out.println (ivals[i]);
}

答案 2 :(得分:0)

如果您尝试编写算法的实现,那么继续。但是如果你打算在代码中使用它,那么下面就足够了。

用于就地反转阵列:

Collections.reverse(Arrays.asList(array));

它起作用,因为Arrays.asList将一个直写代理返回到原始数组。

相关问题