2017-05-04 22 views
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(); 
    } 
+2

储存于一个字符串数组并返回? –

+2

创建一个StringBuilder对象并将当前正在打印的所有内容附加到它。然后返回StringBuilder的'toString()'。 – Eran

+0

我不知道上下文,但*返回*字符串似乎并不是人们通常想要的。换句话说,我有种异味[XY-Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)。我宁愿创建一个'Grid'类,然后用你在这里的代码覆盖'toString()'方法。也许给我们提供更多的背景,以便我们提供更好的建议。 – domsson

回答

2

创建一个StringBuilder

StringBuilder result = new StringBuilder(); 

更换每

System.out.println(); 

result.append("\n"); 

并更换

System.out.print(string); 

result.append(string); 

在方法的末尾添加

return result.toString();