【问题标题】:How can I reverse my Int Array? [closed]如何反转我的 Int 数组? [关闭]
【发布时间】:2016-07-10 04:10:14
【问题描述】:
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);
    }

}

【问题讨论】:

  • System.out.println(d); 这不是你打印数组的方式 -> What's the simplest way to print a Java array?
  • 为什么将数组的长度除以 2?
  • 我的 anwser 是否帮助您解决了 Gustavo Bruno 的问题?
  • 您应该稍微清理一下该代码。 Camel case 和snake case,缩写的方法名,违反单一职责原则。。当你的代码让我眯眼时,很难提供帮助。
  • 是的。我的问题解决了。谢谢大家。我真的很难找到反向数组的解决方案。

标签: java


【解决方案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])
     }         
  }

【讨论】:

    【解决方案2】:

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

    就地反转数组:

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

    因为 Arrays.asList 返回原始数组的直写代理,所以它可以工作。

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 2021-12-11
        • 2023-03-18
        • 2018-05-11
        • 1970-01-01
        • 2015-07-25
        • 1970-01-01
        • 1970-01-01
        • 2023-04-05
        • 1970-01-01
        相关资源
        最近更新 更多