反转阵列

时间:2015-12-09 04:16:34

标签: java arrays

我刚开始使用数组,并想知道我必须添加到此代码中以使数组以相反的顺序打印出来。

import java.util.Scanner;
public class Program10 {

static Scanner keyboard = new Scanner(System.in);

public static void main(String[] args) {

    int[] myArr = {5, 3, 2, 6, 14, 8, 9, 14};
    int[] myArr2 = {6, 7, 8, 9, 10};

    System.out.println("First array before being arranged");
    printArray(myArr);
    rearrangeArray(myArr);
    System.out.println("First array after being arranged");
    printArray(myArr);

    System.out.println("Second array before being arranged");
    printArray(myArr2);
    rearrangeArray(myArr2);
    System.out.println("Second array after being arranged");
    printArray(myArr2);                     

}

public static void printArray(int[] a){

}

public static void rearrangeArray(int[] b){

}
}

5 个答案:

答案 0 :(得分:3)

public void printRev(int[] x){
   for(int i = x.length-1; i>=0; i--){
      System.out.print(x[i] + " ");
   }
}

在这个例子中,你所要做的就是从后到前。

答案 1 :(得分:0)

1。)通过简单的迭代来打印数组。

2.。)无需重新排列数组,只需按相反的顺序打印。

static Scanner keyboard = new Scanner(System.in);

public static void main(String[] args) {

    int[] myArr = { 5, 3, 2, 6, 14, 8, 9, 14 };
    int[] myArr2 = { 6, 7, 8, 9, 10 };

    System.out.println("First array before being arranged");
    printArray(myArr);
    rearrangeArray(myArr);
    System.out.println("First array after being arranged");
    printArray(myArr);

    System.out.println("Second array before being arranged");
    printArray(myArr2);
    rearrangeArray(myArr2);
    System.out.println("Second array after being arranged");
    printArray(myArr2);

}

public static void printArray(int[] a) {
    for (int element : a) {
        System.out.print(element);
    }
}

public static void rearrangeArray(int[] b) {
    for(int i = b.length-1; i>=0; i--){
          System.out.print(b[i]);
       }
}

<强>输出

First array before being arranged
5326148914First array after being arranged
1498146235Second array before being arranged
678910Second array after being arranged
109876

答案 2 :(得分:0)

为了后人,这里是Java 8中使用Stream API执行此操作的方法。如果您只是使用简单和小型数组,这是过度的,但是对于将来可能出现的事情很有用。

int[] myArr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Arrays.stream(myArr)
      .boxed() // required for the collect operation
      .collect(Collectors.toCollection(LinkedList::new))
      .descendingIterator() // is only present with a LinkedList
      .forEachRemaining(System.out::println);

答案 3 :(得分:0)

如何将数组转换为ArrayList,然后将其传递给Collections.reverse(array);以简单地反转数组。

Collections.reverse(new ArrayList(Arrays.asList(myArr)));

答案 4 :(得分:-1)

public static void printArray(int[] a){
    for (int i = 0; i < a.length; i++){
        System.out.print(a[i] + " ");
    }
}

public static void rearrangeArray(int[] b){
    int start = 0;
    int end = b.length - 1;
    while (start < end){
        b[start] = b[start] + b[end];
        b[end] = b[start] - b[end];
        b[start] = b[start] - b[end];
        start++;
        end--;
    }
}

我认为你已经熟悉了Java! :)