繁体   English   中英

如何从Java中的另一个方法正确调用2D数组?

[英]How to correctly call a 2D array from another method in java?

基本上,我试图创建一个对象,并通过main方法/构造函数对其进行调用。 当我打印出来时,我得到一个列表,但是我需要像一张桌子一样打印出来。 这是代码:

import java.util.Arrays;

public class test2 {
    public static String[][] makeTable(int mouseLocationRow, int mouseLocationColumn) {
        int rows = 12;
        int columns = 12;
        String[][] a = new String[rows][columns];
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                a[i][j] =   "#";
            }
        }
        a[mouseLocationRow][mouseLocationColumn] = "&";
        return a;
    }
    public static void main(String[] args) {
        int a = 5;
        int b = 5;
        System.out.println(Arrays.deepToString(makeTable(a, b)));
    }

}

这是输出:

[[#, #, #, #, #, #, #, #, #, #, #, #], [#, #, #, #, #, #, #, #, #, #, #, #], [#, #, #, #, #, #, #, #, #, #, #, #], [#, #, #, #, #, #, #, #, #, #, #, #], [#, #, #, #, #, #, #, #, #, #, #, #], [#, #, #, #, #, &, #, #, #, #, #, #], [#, #, #, #, #, #, #, #, #, #, #, #], [#, #, #, #, #, #, #, #, #, #, #, #], [#, #, #, #, #, #, #, #, #, #, #, #], [#, #, #, #, #, #, #, #, #, #, #, #], [#, #, #, #, #, #, #, #, #, #, #, #], [#, #, #, #, #, #, #, #, #, #, #, #]]

它应该是这样的:

############
############
############
############
############
#####&######
############
############
############
############
############
############

如何使输出看起来像应该的样子?

您可能要使用char [] []而不是String [] []。

然后,要显示,请使用以下类似printTable()的内容:

import java.util.Arrays;

public class test2 {
    public static char[][] makeTable(int mouseLocationRow, int mouseLocationColumn) {
        int rows = 12;
        int columns = 12;
        char[][] table = new char[rows][columns];

        for (char[] row : table)
            Arrays.fill(row, '#');

        table[mouseLocationRow][mouseLocationColumn] = '&';
        return table;
    }

    public static void printTable(char[][] table) {
        for (char[] row : table)
            System.out.println(new String(row));
    }

    public static void main(String[] args) {
        int a = 5;
        int b = 5;
        printTable(makeTable(a, b));
    }
}

您是否正在寻找类似的东西:

 public void print2DArray(int[][] arr) {
    for (int row = 0; row < arr.length; row++) {
        for (int col = 0; col < arr[row].length; col++) {
            System.out.print(" " + arr[row][col]);
        }
        System.out.println();
    }
}

然后从您的主要方法中调用它,如下所示:

    int[][] arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
    print2DArray(arr);

还是我错过了什么?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM