将自定义 2D 数组打印为矩阵



鉴于我当前的代码,我如何以矩阵格式输出它?我当前的输出方法只是在一条直线上列出数组。但是,我需要将它们堆叠在相应的输入参数中,以便 3x3 输入产生 3x3 输出。谢谢!

import java.util.Scanner;
for(int row = 0; row < rows; row++){
    for( int column = 0; column < columns; column++){
        System.out.print(array2d[row][column] + " ");
    }
    System.out.println();
}
这将打印出

一行,然后移动到下一行并打印出其内容,依此类推......使用您提供的代码进行了测试并正常工作。

编辑 - 添加了所需方式的代码:

public static void main(String[] args) {
    Scanner scan =new Scanner(System.in); //creates scanner object
    System.out.println("How many rows to fill?"); //prompts user how many numbers they want to store in array
    int rows = scan.nextInt(); //takes input for response
    System.out.println("How many columns to fill?");
    int columns = scan.nextInt();
    int[][] array2d=new int[rows][columns]; //array for the elements
    for(int row=0;row<rows;row++) 
        for (int column=0; column < columns; column++)
        {
        System.out.println("Enter Element #" + row + column + ": "); //Stops at each element for next input
        array2d[row][column]=scan.nextInt(); //Takes in current input
        }
    System.out.println(Arrays.deepToString(array2d));
    String[][] split = new String[1][rows];
    split[0] = (Arrays.deepToString(array2d)).split(Pattern.quote("], [")); //split at the comma
    for(int row = 0; row < rows; row++){
        System.out.println(split[0][row]);
    }
    scan.close();
}
for (int i =0; i < rows; i++) { 
    for (int j = 0; j < columns ; j++) { 
        System.out.print(" " + array2d[i][j]); 
    } 
    System.out.println(""); 
} 

最新更新