需要帮助打印出二维数组中的字符串

need help printing out a string in a 2d array

我正在尝试使用 JOptionPane 在消息对话框中打印二维数组。我应该创建一个使用 for 循环将数组转换为字符串的方法。我已经尝试了很多,但它似乎并没有让逻辑按照我想要的方式工作。这是我目前所拥有的。

public static String toString(int[][] array) {
        String res = "{";
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j <array[i].length; j++) {
                res += array[i][j];
                if(j < array.length-1) {
                    res += ","; 
                }
                if (i < array.length-1) {
                    res += "}";
                }

            }

        }res += "}";
        return res;
    }

主要class:

import javax.swing.JOptionPane;

import arrays.Integer2dArrays;

public class Exercise4b {
    public void testArray(int[][] array) {
        String message = "";
        message += "toString: " + Integer2dArrays.toString( array ) + "\n";
        message += "elements: " + Integer2dArrays.elements( array ) + "\n";
        message += "max: " + Integer2dArrays.max( array ) + "\n";
        message += "min: " + Integer2dArrays.min( array ) + "\n";
        message += "sum: " + Integer2dArrays.sum( array ) + "\n";
        message += "average: " + String.format( "%1.2f", Integer2dArrays.average( array ) ) + "\n";
        JOptionPane.showMessageDialog( null, message );
    }

    public static void main(String[] args) {
        Exercise4b e4b = new Exercise4b();
        int[][] test1 = {{1,2,3,4},{-5,-6,-7,-18},{10,9,8,7}};
        int[][] test2 = {{1,2,3,4,5,6},{-7,-8,-9},{2,5,8,11,8},{6,4}};
        e4b.testArray(test1);
        e4b.testArray(test2);        
    }
}

最终结果应该是这样的:

也许您可以使用 deepToString 来实现您的结果?

String result = Arrays.deepToString(test1)
            .replace("[", "{")
            .replace("]", "}")
            .replace(" ", "");

您缺少的常见逻辑是

    if (i > 0)
            res += ",";

因此,要正确获取它,您的方法 toString 应该是这样的:

  public static String toString(int[][] array) {
    String res = "{";
    for (int i = 0; i < array.length; i++) {
        if (i > 0)
            res += ",";
        res += "{";
        for (int j = 0; j <array[i].length; j++) {
             if (j> 0)
                res += ",";
            res += array[i][j];
        }
      res += "}";

    }
    res += "}";
    return res;
}