从函数/方法返回for循环打印网格

时间:2017-05-04 12:05:21

标签: java function return

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

1 个答案:

答案 0 :(得分:2)

创建一个StringBuilder

StringBuilder result = new StringBuilder();

替换每个

System.out.println();

result.append("\n");

并替换

System.out.print(string);

result.append(string);

在方法结束时,添加

return result.toString();