【问题标题】:Printing Custom 2d Array as a Matrix将自定义二维数组打印为矩阵
【发布时间】:2023-03-25 16:17:02
【问题描述】:

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

import java.util.Scanner;

【问题讨论】:

    标签: java arrays format output


    【解决方案1】:
    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();
    }
    

    【讨论】:

    • 非常感谢!有没有办法用我最初使用的 Array.DeeptoString 方法来做到这一点?只是好奇,我实际上不必这样做
    • 绝对是的!在, 处拆分Arrays.deepToString(array2d) 并将它们放入另一个数组,其大小基于array2d[][] 的行数。然后使用相同的 for 循环逻辑将其打印出来。如果您需要帮助,请告诉我。如果对您有帮助,请接受我的回答!
    • 好的,我想通了(虽然现在看起来有点糟糕,但您可以自己确定格式;))。它采用Arrays.deepToString(array2d) 并将其拆分并输出。您感兴趣的线路是split[0] = (Arrays.deepToString(array2d)).split(Pattern.quote("], ["));。
    【解决方案2】:
    for (int i =0; i < rows; i++) { 
        for (int j = 0; j < columns ; j++) { 
            System.out.print(" " + array2d[i][j]); 
        } 
        System.out.println(""); 
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-20
      • 2012-10-01
      • 2011-07-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-19
      • 1970-01-01
      相关资源
      最近更新 更多