如何在java中双重输入数组?

时间:2018-01-23 05:49:00

标签: java arrays

所以,我正在尝试使用6,7,34,7,6的数组输入并创建一个方法来使输出为6 6 7 7 34 34 7 7 6 6

我该怎么做?

到目前为止,我有:

public int [] twice (int[] ary)

int [] A =  new int [ary.length * 2]

A [0] = 6;
A [1] = 7;
A [2] = 34;
A [3] = 7;
A [4] = 6;

但我不知道从哪里去。

5 个答案:

答案 0 :(得分:3)

试试这个:

public static int[] twice(int[] ary) {
    int[] A = new int[ary.length * 2];
    for(int i=0, j=0;j<ary.length;i=i+2,j++) {
        A[i] = A[i+1] = ary[j];
    }
    return A;
}

答案 1 :(得分:0)

只需使用两个for循环

{
    for (int i=0;i<5;i++) System.print(ary[i]);
for (int i=0;i<5;i++) System.print(ary[4-i]);
}

答案 2 :(得分:0)

public static int [] twice (int[] ary)
    {
      int [] A =  new int [ary.length * 2];
      //take 2 variables one to point input array and 1 for output array
        int c = 0;
        for(int n: ary) {
         //put each element of input array twice in output array
          A[c] = A[c+1] = n;
          c += 2;
      }
      //return output array
      return A;
    }

答案 3 :(得分:0)

由于您的输入值看起来像他们已经排序,然后您再次按降序将相同的值放到目标数组中,您可能希望尝试首先根据您要实现的目标对输入进行排序:< / p>

public int [] twice(int[] ary) {
    int[] temporary = new int[ary.length];
    for (int i = 0; i < ary.length; i++) { // copying ary to temporary
        temporary[i] = ary[i];
    }
    Arrays.sort(temporary); // sorting  temporary in ascending order
    int[] result = new int[ary.length * 2]; // creating double sized result array
    for(int i = 0; i < temporary.length; i++) { // copying sorted contents of temporary at the beginning of result array
        result[i] = temporary[i];
    }
    int j = 0 ;
    for(int i = result.length - 1; i >= result.length / 2; i--) { // inserting contents of temporary from the end of result array to the middle ("from right to left")
        result[i] = temporary[j++];
    }
    return result; // returning result array
}

答案 4 :(得分:0)

如果你想在最后添加值

// Java程序解释系统类方法 - arraycopy()

import java.lang.*;
import java.util.Arrays;
public class NewClass
{
    public static void main(String[] args)
    {
        int s[] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
        int d[] = Arrays.copyOf(s, s.length*2);

        int source_arr[], sourcePos, dest_arr[], destPos, len;
        source_arr = s;
        sourcePos = 0;
        dest_arr = d;
        destPos = s.length;
        len = s.length;

        // Use of arraycopy() method
        System.arraycopy(source_arr, sourcePos, dest_arr, 
                                            destPos, len);
        // Print elements of destination after
        System.out.print("final dest_array : ");
        for (int i = 0; i < d.length; i++)
            System.out.print(d[i] + " ");
    }
}