我正在尝试将此二维字符数组转换为字符串。问题是,即使输入数组远未达到 100,000 个字符,它仍会输出 100,000 个字符。将二维字符数组转换为字符串的正确方法是什么?
public String printMaze(char[][] maze) {
String s= "";
for(int i=0;i<maze.length;i++){
for(int j=0; i<maze[i].length;j++){
s= maze.toString();;
}
}
return s;
}
最佳答案
你的内部循环有问题,而且我没有看到你实际上从二维字符数组中得到了一个字符串。这是内循环的问题:
for (int j=0; i < maze[i].length; j++) {
// ^^^^ this will always be true for certain values of i
// it should be j < maze[i].length
s= maze.toString();;
}
换句话说,你的内部循环可能会永远旋转,具体取决于迷宫的边界。相反,请尝试以下代码:
public String printMaze(char[][] maze) {
String s = "";
for (int i=0; i < maze.length; i++) {
for (int j=0; j < maze[i].length; j++) {
s += maze[i][j];
}
// uncomment next line if you want the maze to have rows
// s += "\n";
}
return s.toString();
}
但正如 @ElliottFrisch 提到的,您可以只返回 Arrays.deepToString(maze)。
关于java - 将二维字符数组转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43578522/