如何返回以下函数/方法中打印的网格?我正在使用一个String函数/方法,但我完全不确定如何在主类中返回此函数/方法中打印的内容。
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();
}
答案 0 :(得分:2)
创建一个StringBuilder
StringBuilder result = new StringBuilder();
替换每个
System.out.println();
与
result.append("\n");
并替换
System.out.print(string);
带
result.append(string);
在方法结束时,添加
return result.toString();