简体   繁体   English

将2d对象数组存储为字符串

[英]Store 2d array of objects as string

I have a 2D array of objects of class Cell. 我有一个Cell类对象的2D数组。 In a separate Maze class I read in the 2D array from a file, and now I need to have a method that returns the entire array as a String. 在一个单独的Maze类中,我从一个文件读取2D数组,现在我需要一个方法将整个数组作为String返回。 I'm not sure how to go about doing this, any help would be wonderful(I have a method in the Cell class that will return the cell as a string). 我不知道该怎么做,任何帮助都会很精彩(我在Cell类中有一个方法将单元格作为字符串返回)。

Print your matrix with 2 nested loops: 使用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);

Granted that your Cell object has a toString() method. 假设您的Cell对象具有toString()方法。

You can use Arrays.deepToString() method to print String of multidimensional array 您可以使用Arrays.deepToString()方法打印多维数组的String

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

Output 产量

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

For this to work you need to have toString() method inside your cell class. 为此,您需要在单元类中使用toString()方法。 Otherwise default toString() method will be used. 否则将使用默认的toString()方法。

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

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