0
如何返回打印在下面的函数/方法中的网格?我正在使用String函数/方法,但我不确定我将如何返回在我的主类中的此函数/方法中打印的内容。从函数/方法返回一个for循环打印的网格
public static String Grid(){
int[][] map = new int[4][4];
map[x][y] = entry;
int counter = 0;
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[i].length; j++) {
if (counter != 2) {
if (j < 2) {
System.out.print("+---");
} else if (j == 2) {
System.out.print("++---+");
} else {
System.out.print("---+");
}
}
else{
if (j < 2) {
System.out.print("+===");
} else if (j == 2) {
System.out.print("++===+");
} else {
System.out.print("===+");
}
}
}
System.out.println();
for (int j = 0; j < map[i].length; j++) {
if (j < 2) {
System.out.print("| " + map[i][j] + " ");
} else if (j == 2) {
System.out.print("|| " + map[i][j]);
} else {
System.out.print(" | " + map[i][j] + " |");
}
}
System.out.println();
counter++;
}
System.out.print("+---+---++---+---+");
System.out.println();
}
储存于一个字符串数组并返回? –
创建一个StringBuilder对象并将当前正在打印的所有内容附加到它。然后返回StringBuilder的'toString()'。 – Eran
我不知道上下文,但*返回*字符串似乎并不是人们通常想要的。换句话说,我有种异味[XY-Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)。我宁愿创建一个'Grid'类,然后用你在这里的代码覆盖'toString()'方法。也许给我们提供更多的背景,以便我们提供更好的建议。 – domsson