如何返回下面的函数/方法中打印的网格?我正在使用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();
    }

最佳答案

创建一个StringBuilder

StringBuilder result = new StringBuilder();


更换每一个

System.out.println();




result.append("\n");


并更换

System.out.print(string);




result.append(string);


在方法末尾,添加

return result.toString();

10-07 19:15
查看更多