【问题标题】:How to call a method that deals with arrays如何调用处理数组的方法
【发布时间】:2014-03-25 23:07:52
【问题描述】:

提示:编写一个反转数组中元素序列的方法。

例如,如果你用数组调用方法

1 4 9 16 9 7 4 9 11

然后数组变为

11 9 4 7 9 16 9 4 1

这是我目前所拥有的。我不知道如何调用该方法...

public static void main(String[] args) {
    int [] array = {1,4,9,16,9,7,4,9,11};

    System.out.println(reverse(array[]));
}
public static void reverse (int[]a){
    for (int i = 0; i < a.length/2; i++){
        double temp = a[i];
        a[i] = a[a.length - i -1];
        temp = a[a.length - i - 1];
    }
}

【问题讨论】:

标签: java arrays methods


【解决方案1】:

很简单,你的reverse方法也有一点错误,这里是:

import java.util.Arrays;

public class JavaApplication118 {

    public static void main(String[] args) {
        int[] array = {1, 4, 9, 16, 9, 7, 4, 9, 11, 5};
        reverse(array); //here you call the method
        System.out.println(Arrays.toString(array)); //print the array, using Arrays method
    }

    public static void reverse(int[] a) {
        for (int i = 0; i < a.length / 2; i++) {
            int temp = a[i];
            a[i] = a[a.length - i - 1];
            a[a.length - i - 1] = temp;
        }
    }
}

【讨论】:

    【解决方案2】:

    如果您不必自己实现,可以使用 Apache Commons Lang 工具。

    ArrayUtils.reverse(..)
    

    完全按照你的意愿去做。

    在您的代码块中,您分配变量temp 两次。但是第二次应该分配它的值。所以这是对的:

    public static void reverse (int[]a){
      for (int i = 0; i < a.length/2; i++){
        double temp = a[i];
        a[i] = a[a.length - i -1];
        a[a.length - i - 1] = temp;  //<--- here was the mistake
      }
    }
    

    【讨论】:

    • 但这并不能回答 OP 的问题。
    猜你喜欢
    • 1970-01-01
    • 2015-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多