【问题标题】:Store 2d array of objects as string将二维对象数组存储为字符串
【发布时间】:2012-09-29 05:02:46
【问题描述】:

我有一个 Cell 类对象的二维数组。在一个单独的 Maze 类中,我从文件中读取 2D 数组,现在我需要一个将整个数组作为字符串返回的方法。我不知道该怎么做,任何帮助都会很棒(我在 Cell 类中有一个方法可以将单元格作为字符串返回)。

【问题讨论】:

标签: java arrays string multidimensional-array maze


【解决方案1】:

使用 2 个嵌套循环打印您的矩阵:

String temp = "";

// foreach row...
for( int i = 0; i < cells.length; i++ )
{

    // ... move across columns
    for( int j = 0; j < cells[i].length; j++ )
    {

        temp += (cells[i][j] + " ");

    }

    // let's move to a new line
    temp += "\n";

}

System.out.println(temp);

您的 Cell 对象有一个 toString() 方法。

【讨论】:

  • 我对内部 for 循环感到困惑? i
【解决方案2】:

您可以使用Arrays.deepToString()方法打印多维数组的字符串

    String[][] str = new String[][]{{"a","b"},{"c","d"}};
    System.out.println(Arrays.deepToString(str));

输出

 [[a, b], [c, d]]

为此,您需要在单元类中包含toString() 方法。否则将使用默认的toString() 方法。

【讨论】:

    猜你喜欢
    • 2021-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-23
    • 1970-01-01
    • 2019-08-10
    • 1970-01-01
    相关资源
    最近更新 更多