If I wanted this list
List<Character> Board = Arrays.asList('1', '2', '3', '4', '5', '6', '7', '8', '9');
to be printed as
1 2 3
4 5 6
7 8 9
How exactly would I do that? Any help would be nice.
CodePudding user response:
You can do it as:
for (int i = 0; i < 3; i ) {
for (int j = 0; j < 3; j ) {
System.out.print(Board.get(i * 3 j) " ");
}
System.out.println();
}
CodePudding user response:
Assuming exactly 3 x 3 size:
for (i=0; i<9; i =3) {
for (j=i; j<i 3; j ) {
System.out.printf(" %c", Board.get(j));
}
System.out.println();
}
Generalizing to work for any N x M is left as an exercise for the reader.
CodePudding user response:
You want a dynamic separator. The first character is special, in that you want no separator. Otherwise, default to a space. Every third character change it to two newlines. Also, Java naming convention would be board
(not Board
). Something like,
String sep = "";
for (int i = 0; i < board.size(); i ) {
System.out.printf("%s%c", sep, board.get(i));
sep = (i 1) % 3 == 0 ? "\n\n" : " ";
}
Outputs (as requested)
1 2 3
4 5 6
7 8 9