2013-12-17 387 views
1

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

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

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 

回答

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();  
     } 
+0

谢谢!但是,如果我已经声明了一个大的2d数组(可以说超过5000行),我该怎么做第一个循环(行)? – user3086819

+0

几乎在那里!现在,如果我声明int firstarray [] [] = {{8,9,10,11},{12,13,14,15},{1,2,3},{15,88,99}}; 我不会在输出中显示最后2行。我想我需要使用一些动态变量,因为我将不得不使用后来不同的数组(使用不同的声明) – user3086819

+0

检查并让我知道兄弟... – Ulaga

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个数。