java - 将自定义二维数组打印为矩阵

标签 java arrays format output

鉴于我当前的代码,我如何以矩阵格式输出它?我当前的输出方法只是以直线列出数组。不过,我需要将它们堆叠在相应的输入参数中,以便 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();
}

关于java - 将自定义二维数组打印为矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21815820/

相关文章:

java - 使用 Mysql 为 Java 应用程序进行数据库镜像

c# - 使用 Newtonsoft.Json c# 序列化数组

python - 将数组形状转换为字符串

java - Wicket 组件不会通过 AJAX 刷新

java - CryptoJS 加密 HMACSha256 与 Java 不同

java - 将 UTC 日期四舍五入到最接近的 5 分钟

java - 如何在opencv Java中将int[][]转换为Mat?

java - 两个集合的并集,操作数组 Java

PHP strtotime() 将日期设置为默认值

php - 在 PHP 中将一种日期格式转换为另一种日期格式