2维数组打印行作为列java

时间:2014-03-04 12:16:16

标签: java arrays

我们被要求打印这个2D数组,列为行

例如:第一列是20,11,27,必须打印:

20
 11个
 27

到目前为止,这是我的代码,我甚至无法正常打印列,您是否知道问题是什么,以及是否可以帮我找到问题的解决方案?

public class TwoDimensionalArrays
{
public static void main (String args[])
{
    final int size1 = 2, size2 = 4, size3 = 5;
    int [][] numbers = {{20,25,34,19,33}, {11,17,15,45,26}, {27,22,9,41,13}};        
    int row = 0, col = 0;

        for(row = 0; row <= size1; row++); //loops through rows
        {
            for(col = 0; col <= size2; col++); //loops through columns
            {
                System.out.println(numbers[row][col]);
            }
        System.out.print("\n"); //takes a new line before each new print
        }
    }
 }

4 个答案:

答案 0 :(得分:3)

在循环结束时删除;

像这样:

for (row = 0; row <= size1; row++) //loops through rows
 {
   for (col = 0; col <= size2; col++) //loops through columns
    {
       System.out.print(numbers[row][col]+" ");
     }
    System.out.print("\n"); //takes a new line before each new print
  }

输出:

20 25 34 19 33 
11 17 15 45 26 
27 22 9 41 13 

答案 1 :(得分:1)

您不应该依赖多维数组的某些预定义大小(更好的名称是数组数组)。始终使用数组的实际大小,例如numbers.lengthnumbers[0].length,或者像这样使用for-each:

int [][] numbers = {{20,25,34,19,33}, {11,17,15,45,26}, {27,22,9,41,13}};        

for (int[] row: numbers){
    for (int num: row){
        System.out.print(num+" ");
    }
    System.out.println();
}

结果如下:

20 25 34 19 33 
11 17 15 45 26 
27 22 9 41 13 

如果您想要转置,可以这样做:

    for(int i = 0; i < numbers[0].length; i++) {
        for(int j = 0; j < numbers.length; j++) {
            System.out.print(numbers[j][i]+"\t");
        }
        System.out.println();
    }

现在的结果是:

20  11  27  
25  17  22  
34  15  9   
19  45  41  
33  26  13  

注意:数组数组中只有行和列,只有维度。

答案 2 :(得分:0)

您不需要直接提供尺寸,但您可能需要计算(或者,更简单,提供)元素的最大长度。

打印可能如下所示:

int maxDigits = 2; //provided or calculated
int [][] numbers = {{20,25,34,19,33}, {11,17,15,45,26}, {27,22,9,41,13}};        
for( int[] row : numbers ) {
  for( int n : row) {
    System.out.print( String.format("%" + maxDigits + "d ", n) ); //creates the format string "%2d" for 2 digits maximum
  }
  System.out.println(); //takes a new line before each new print
}

请注意,您应使用System.out.print()打印而不换行符。

输出将如下所示:

20 25 34 19 33 
11 17 15 45 26 
27 22  9 41 13 

答案 3 :(得分:0)

public class rwr {

    public static void main(String[] args){ 

final int size1=2,size2=4,size3=5;

        int[][] number={{34,34,33,33,44},{22,23,24,23,24},{23,44,55,66,66}};

        int row=0,col=0;

        for(row=0;row<=size1;row++){

            for(col=0;col<=size2;col++){

                System.out.print(number[row][col]+"\t");

            }
            System.out.print(" \n");
        }
    }

}
run:
34  34  33  33  44   
22  23  24  23  24   
23  44  55  66  66   
BUILD SUCCESSFUL (total time: 0 seconds)