将行打印为列的二维数组 java



我们被要求打印这个 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
        }
    }
 }

删除循环末尾的;

喜欢这个:

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 

你不应该依赖多维数组的一些预定义大小(更好的名称是数组数组)。始终使用数组的实际大小,如 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  

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

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

然后打印可能如下所示:

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 
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)

最新更新