对齐二维阵列打印输出[Java]

时间:2013-12-17 10:51:22

标签: java arrays printing console invert

我声明了一个带有一些值的2D int数组,我需要在控制台上反转行/列。 第一行必须垂直显示为第一列,第二行必须垂直显示为第二列,依此类推。 因此,例如,[0] [0],[0] [1],[0] [2]的值应垂直打印,第二行的即将到来的值也应垂直对齐。

到目前为止,这是我的代码!

public class Print {
    public static void main(String[] args) {

        int firstarray[][] = {{8,9,10,11},{12,13,14,15}};

        System.out.println("This is the inverted array");
        display(firstarray);

    }

public static void display (int x[][]){
    for(int row=0; row<x.length; row++){
        for(int column = 0; column<x[row].length; column++){
            System.out.println(x[row][column] + "\t");
        }
        System.out.print("\n");
    }   
}   
}

电流输出(未正确对齐):

This is the inverted array
8   
9   
10  
11  

12  
13  
14  
15  

正确的输出应该是:

This is the inverted array
8,12    
9,13    
10,14   
11,15   

2 个答案:

答案 0 :(得分:0)

只需更改你的for循环,

    for(int row=0; row<1; row++){
        for(int column = 0; column<x[row].length; column++){
            System.out.println(x[row][column] + "\t"+x[row+1][column] );
        }
        System.out.print("\n");
    } 

进入下面这将有效,即使你有5000行,

     for(int row=0; row<x.length-1; row++){
        for (int column = 0; column < x.length; column++) {
            System.out.print(x[column][row] + "\t" );   
            }
            System.out.println();       
      }

答案 1 :(得分:0)

您只需更改您扫描的行数限制:您可以创建预设号码(就像我一样):

public class Print {

public static int myBigInt;

public Print() {
}

public static void main(String[] args) {
    myBigInt = 5000;
    int myArray[][] = new int[myBigInt][myBigInt];

    for (int i = 0; i < myBigInt - 1; i++) {
        for (int j = 0; j < myBigInt - 1; j++) {
            int x = (int) (Math.random() * (50));
            int y = (int) (Math.random() * (30) / 2);
            myArray[i][j] = (x + ((x) + (y * 4)) / 2) + (y + ((x * 7) + (y)) / 2);
        }
    }
    System.out.println("This is the inverted array");
    display(myArray);
}

public static void display(int x[][]) {
    for (int row = 0; row < myBigInt - 1; row++) {
        for (int column = 0; column < x[row].length; column++) {
            System.out.println(x[row][column] + "\t" + x[row + 1][column]);
        }
        System.out.print("\n");
    }
}

}

甚至可以为限制生成随机数,例如:

myBigInt = (int) (Math.random() * (500));

这样,您可以更改数组的大小,而无需更改任何其他内容。

我对随机数生成器有点愚蠢,但这会在并排数组中打印出4999组5000个数字。