You should strive to write your code without special cases. Having more code paths makes your code harder to analyze. Actually, your general case already works to cover everything.
What is the point of count
? Isn't it always i - 1
?
While for(int i = 1; i <= size; i++)
is not wrong, it would be more idiomatic in Java to write for (int i = 0; i < size; i++)
unless you had a good reason to count starting from 1.
Personally, I prefer a ternary conditional to better express the fact that one way or another, something will get printed. That's a matter of taste, though.
public static void xo(int size) {
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
System.out.print((row == col) || (row + col == size - 1) ? "x"
: "o");
}
System.out.println();
}
}
If you care about performance, then you would be better off building the entire result first, then printing the entire string in one System.out.print()
call.
Here's one way to do it, but it's rather ugly.
public static void xo(int size) {
char[] result = new char[size * (size + 1)];
java.util.Arrays.fill(result, 'o');
for (int i = 0; i < result.length; i += size + 2) {
result[i] = 'x';
}
for (int i = result.length - size - 1; i >= 0; i -= size) {
result[i] = 'x';
}
for (int rowEnd = size; rowEnd < result.length; rowEnd += size + 1) {
result[rowEnd] = '\n';
}
System.out.print(new String(result));
}