我想寫一個toString()方法將一個代表迷宮的2d Char數組轉換爲字符串表示形式。toString()方法,返回一個迷宮的字符串表示形式
public String toString(){
String s = "";
for(int i = 0; i < map.length;i++){
s += Arrays.toString(map[i]);
}
return s;
}
public static void main(String[] args){
Maze maze = new Maze();
String filename = args[0];
maze.initializeFromFile(filename);
String path = maze.findPath();
map[startRow][startCol] = 'S';
System.out.println(map.toString());
System.out.println(path);
}
但是,這給了我這樣的輸出。我在這裏讀到這是指針地址或與內存位置有關的內容,但我不知道該如何處理。當我在我的Main中使用一個簡單的循環來打印每一行時,我可以得到我想要的輸出,但每當我嘗試使用這種方法時,我總是會得到這種輸出。
[[[email protected]
這是我從一個文本文件給出的迷宮。
10 10
##########
# #
# ### #
# # G #
# # #
# #
# #
# #######
# S #
##########
這是我我的初始化字符數組
public class Maze {
public static char[][] map;
public static int startRow;
public static int startCol;
public static int mapHeight;
public static int mapWidth;
public void initializeFromFile(String filename){
try {
Scanner scanner = new Scanner(new File(filename));
mapHeight = scanner.nextInt();
mapWidth = scanner.nextInt();
scanner.nextLine();
map = new char[mapHeight][mapWidth];
for(int i = 0; i < map.length;i++){
String line = scanner.nextLine();
map[i] = line.toCharArray();
for(int j = 0; j < map[i].length;j++){
if(map[i][j] == 'S'){
startRow = i;
startCol = j;
}
}
}
scanner.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
通常'toString'方法假設返回簡單的一行字符串,其中包含關於對象的信息,這些信息可以很容易地包含在日誌文件中。如果您的方法需要生成多行響應,那麼可能會創建單獨的方法,如'void printMaze()'而不是'toString()'。你也不應該在'try'塊中關閉你的資源,因爲如果在這行之前會發生什麼壞事,你永遠不會調用'close()'方法。將它移到'finally'塊,或者更好地開始使用try-with-resources。 – Pshemo