我有这个
public String toString()
{
String s = "";
for (int r = 0; r != 7 ; r++)
{
for (int c = 0; c != 7 ; c++)
{
s += String.format("%02d " ,board[r][c]);
}
}
return s;
}
我需要它像这样返回
01 04 39 20 53 06 37 22
40 19 02 05 38 21 52 07
03 46 61 00 57 54 23 36
18 41 56 49 60 00 08 51
47 14 45 58 55 50 35 24
42 17 48 27 00 59 32 09
13 28 15 44 11 30 25 34
16 43 12 29 26 33 10 31
我该怎么做?
答案 0 :(得分:3)
你添加一个空格行但从不添加新行char
public String toString()
{
String s = "";
for (int r = 0; r != 7 ; r++)
{
for (int c = 0; c != 7 ; c++)
{
s += String.format("%02d " ,board[r][c]);
}
s += String.format("%n");
}
return s;
}
%n是与平台无关的新行char
答案 1 :(得分:1)
小提示:使用StringBuilder。在循环中反复追加String
会让每个体面的程序员都畏缩不前。
private static final String NEW_LINE = System.getProperty("line.separator");
public String toString()
{
StringBuilder s = new StringBuilder();
for (int r = 0; r != 7 ; r++)
{
for (int c = 0; c != 7 ; c++)
{
s.append( String.format("%02d ", board[r][c] );
}
// On each outer-loop iteration, add a platform
// independent line separator (e.g. on Linux, it's "\n")
s.append( NEW_LINE );
}
return s.toString();
}
编辑:在@Diego C Nascimento的建议中,新的行分隔符应该是类常量。