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

时间:2018-11-16 15:48:06

标签: java arrays methods tostring

我正在尝试使用JOptionPane在messagedialog中打印出2维数组。我应该创建一个使用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;
    }

主类:

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);        
    }
}

最终结果应如下所示: The end result should look like this

2 个答案:

答案 0 :(得分:1)

也许您可以使用deepToString来达到目标​​?

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

答案 1 :(得分:0)

您缺少的常见逻辑是

    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;
}