需要帮助打印出2d数组中的字符串[重复]

问题描述 投票:-1回答:2

这个问题在这里已有答案:

我试图使用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);        
    }
}

最终结果应如下所示:

java arrays methods tostring
2个回答
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;
}

1
投票

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

String result = Arrays.deepToString(test1)
            .replace("[", "{")
            .replace("]", "}")
            .replace(" ", "");
© www.soinside.com 2019 - 2024. All rights reserved.