JAVA:如何从两个方向输出Array



我的标题听起来可能有点傻,所以下面是解释:

我有一个阵列

int[] a = new int[] { 1, 2, 3, 4, 5, 6 };

最后的输出应该像一样

123321

我已经设法输出了123456和654321,但我不知道如何输出123321:(我只被允许使用一个外循环,在这个循环中,它可以有一个新的循环。

我尝试了不同的方法,但我没能成功,你们能给我一个提示吗?我一开始想的是:

     while(x <=2){
            System.out.print(a[x]); 
            x++;
            if(x==2){
                while(x>0){
                    System.out.print(a[x]);
                    x--;
                }
            }
     }

您应该指定输出必须满足的条件。对于迭代到数组的一半,然后返回到开头,您不需要任何内部循环。试试这个:

int[] a = new int[] { 1, 2, 3, 4, 5, 6 };
for (int i = 0; i < a.length; ++i){
    if (i<a.length/2) System.out.print(a[i]);
    else System.out.print(a[a.length-i-1]);
}

代码的问题是进入了一个无限循环:

while(x <=2){
    System.out.print(a[x]); 
    x++;                        // <-- you increment x until it reaches 2
    if(x==2){                   // <-- x equals to 2
        while(x>0){
        System.out.print(a[x]);
        x--;                    // <-- you decrement x until it reaches 0
    }
}                               // <-- Wow, 0 <= 2 so re-execute the while loop

你可以这样实现它。当您到达数组的中间时,将执行内部循环,直到它将当前索引中的元素打印到0。

int[] a = new int[] { 1, 2, 3, 4, 5, 6 };
int x = 0;
while(x != a.length/2){                 // <-- loop until the middle of the array
    System.out.print(a[x]);
    x++;
    if(x == a.length/2){                // <-- when we reach the middle execute the inner loop
        for(int i = x -1; i >= 0; i--)  // <-- print the elements of the array from current index to 0
            System.out.print(a[i]);
    }
}

Collections:正好相反

    List<Integer> first = new ArrayList<Integer>(Arrays.asList(1, 2, 3, 4, 5, 6 ));
    int half = first.size()/2;      
    List<Integer> out = new ArrayList<Integer>( first.subList(0, half) );       
    Collections.reverse( first.subList( 0, half ) );        
    out.addAll( first.subList( 0, half ) );     
    System.out.println(out); // [1, 2, 3, 3, 2, 1]

最新更新