JAVA:如何在2个方向输出数组

时间:2013-11-18 22:04:01

标签: java arrays

我的标题可能听起来有点傻,所以这里有解释:

我有一个数组

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

End中的输出应该像

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--;
                }
            }
     }

3 个答案:

答案 0 :(得分:4)

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

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]);
}

答案 1 :(得分:2)

代码的问题在于你进入无限循环:

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]);
    }
}

答案 2 :(得分:0)

使用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]