【问题标题】:Using the Reverse Method/ Arrays- How to Print out the Reverse使用反向方法/数组-如何打印反向
【发布时间】:2017-08-26 09:05:48
【问题描述】:
public static void main(String[] args) {
    int[] HwArray = new int[10];
    int count = 0;
    String separate = "";
    for (int i = 0; i < HwArray.length; i++) {
        System.out.print(separate);

        //Generate random numbers
        HwArray[i] = (int) (100 + Math.random() * 100);
        System.out.println("HwArray[" + i + "]=" + HwArray[i]);
    }

    int location = linearSearch(HwArray, 150);
    System.out.println("\nLinear Search Result: " + location);
}

// Reverse the order of all elements, then print HwArray.
public static int[] reverse(int[] list) {
    int[] result = new int[list.length];
    for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {
        result[j] = list[i];
        System.out.println("HwArray[" + i + "]=" + result[j]);
    }

    return result;
}

public static int linearSearch(int[] list, int key) {
    for (int i = 0; i < list.length; i++) {
        if (list[i] == key)
            return i;  //return the index location

    }

    return -1;   //return if number is not found in the index
}

我正在尝试在 Reverse 中打印出元素,但它只会打印出元素。我不确定出了什么问题。

【问题讨论】:

  • HwArray[0]=105 HwArray[1]=151 HwArray[2]=191 HwArray[3]=163 HwArray[4]=186 HwArray[5]=105 HwArray[6]=146 HwArray[7]=141 HwArray[8]=120 HwArray[9]=115 线性搜索结果:-1

标签: java


【解决方案1】:

在提问之前请多研究一下,也许是谷歌“java反向数组”。我就是这样做的,发现这个人问了同样的事情。 Reversing an Array in Java

解决方法很简单:

List<Integer> lst = Arrays.asList(list); //Converts the int "list" into a list.
Collections.reverse(lst); //Reverses the list.
result = list.toArray(lst);

【讨论】:

  • 我从未听说过 Collections.reverse(lst) 这就是我从未使用过它的原因。
  • 没关系,我们都有第一次。 =)(别忘了给我的答案打分=P)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-13
  • 2014-08-22
相关资源
最近更新 更多