一種方式是使用StringJoiner
(Java的8+)和String.format
的組合,例如
import java.util.StringJoiner;
public class Test {
public static void main(String[] args) {
int[][] easyGrid = {
{2, 3, 5, 9, 7, 1, 8, 4, 6},
{4, 7, 1, 2, 8, 6, 9, 3, 5},
{8, 9, 6, 4, 3, 5, 2, 7, 1},
{1, 6, 8, 7, 4, 9, 5, 2, 3},
{7, 4, 9, 5, 2, 3, 1, 6, 8},
{3, 5, 2, 1, 6, 8, 4, 9, 7},
{6, 2, 4, 8, 1, 7, 3, 5, 9},
{9, 1, 3, 6, 5, 2, 7, 8, 4},
{5, 8, 7, 3, 9, 4, 6, 1, 2}};
for (int[] row : easyGrid) {
StringJoiner sj = new StringJoiner(" | ");
for (int col : row) {
sj.add(String.format("%02d", col));
}
System.out.println(sj.toString());
}
}
}
哪個輸出...
02 | 03 | 05 | 09 | 07 | 01 | 08 | 04 | 06
04 | 07 | 01 | 02 | 08 | 06 | 09 | 03 | 05
08 | 09 | 06 | 04 | 03 | 05 | 02 | 07 | 01
01 | 06 | 08 | 07 | 04 | 09 | 05 | 02 | 03
07 | 04 | 09 | 05 | 02 | 03 | 01 | 06 | 08
03 | 05 | 02 | 01 | 06 | 08 | 04 | 09 | 07
06 | 02 | 04 | 08 | 01 | 07 | 03 | 05 | 09
09 | 01 | 03 | 06 | 05 | 02 | 07 | 08 | 04
05 | 08 | 07 | 03 | 09 | 04 | 06 | 01 | 02
您可以使用這些結果生成一些非常複雜的結果。看看formatted strings更多細節
例如...
import java.util.StringJoiner;
public class Test {
public static void main(String[] args) {
int[][] easyGrid = {
{2, 3, 5, 9, 7, 1, 8, 4, 6},
{4, 7, 1, 2, 8, 6, 9, 3, 5},
{8, 9, 6, 4, 3, 5, 2, 7, 1},
{1, 6, 8, 7, 4, 9, 5, 2, 3},
{7, 4, 9, 5, 2, 3, 1, 6, 8},
{3, 5, 2, 1, 6, 8, 4, 9, 7},
{6, 2, 4, 8, 1, 7, 3, 5, 9},
{9, 1, 3, 6, 5, 2, 7, 8, 4},
{5, 8, 7, 3, 9, 4, 6, 1, 2}};
String lineSplit = "";
StringJoiner splitJoiner = new StringJoiner("+", "|", "|");
for (int index = 0; index < easyGrid[0].length; index++) {
splitJoiner.add(String.format("%4s", "").replace(" ", "-"));
}
lineSplit = splitJoiner.toString();
for (int[] row : easyGrid) {
StringJoiner sj = new StringJoiner(" | ", "| ", " |");
for (int col : row) {
sj.add(String.format("%02d", col));
}
System.out.println(lineSplit);
System.out.println(sj.toString());
}
System.out.println(lineSplit);
}
}
,輸出
|----+----+----+----+----+----+----+----+----|
| 02 | 03 | 05 | 09 | 07 | 01 | 08 | 04 | 06 |
|----+----+----+----+----+----+----+----+----|
| 04 | 07 | 01 | 02 | 08 | 06 | 09 | 03 | 05 |
|----+----+----+----+----+----+----+----+----|
| 08 | 09 | 06 | 04 | 03 | 05 | 02 | 07 | 01 |
|----+----+----+----+----+----+----+----+----|
| 01 | 06 | 08 | 07 | 04 | 09 | 05 | 02 | 03 |
|----+----+----+----+----+----+----+----+----|
| 07 | 04 | 09 | 05 | 02 | 03 | 01 | 06 | 08 |
|----+----+----+----+----+----+----+----+----|
| 03 | 05 | 02 | 01 | 06 | 08 | 04 | 09 | 07 |
|----+----+----+----+----+----+----+----+----|
| 06 | 02 | 04 | 08 | 01 | 07 | 03 | 05 | 09 |
|----+----+----+----+----+----+----+----+----|
| 09 | 01 | 03 | 06 | 05 | 02 | 07 | 08 | 04 |
|----+----+----+----+----+----+----+----+----|
| 05 | 08 | 07 | 03 | 09 | 04 | 06 | 01 | 02 |
|----+----+----+----+----+----+----+----+----|