# Create and print a tic-tac-toe board

Write a program by creating an array of 9 integers that represent the positions in the tic-tac-toe board. Once the array is created, assign values to the board and print the contents of the board out. The values for the board are:

• Board Value: X, Integer in Array: 10
• Board Value: O, Integer in Array: 100
• Board Value: Empty, Integer in Array: 0

This is an example of an array that represents a board:

[10|0|0|100|0|10|10|100|0]


Here is what the above array would look like when printed to the screen:

+---+---+---+
| X |   |   |
+---+---+---+
| O |   | X |
+---+---+---+
| X | O |   |
+---+---+---+


And I basically solved the problem:

public class problem5 {

public static void main(String[] args) {

int[] a = new int[9];
a[0] = a[5] = a[6] = 10;
a[3] = a[7] = 100;
a[1] = a[2] = a[4] = a[8] = 0;
String[] b = new String[9];
int x = 0;

while (x < a.length) {
if (a[x] == 10)
b[x] = "X";
else if (a[x] == 100)
b[x] = "O";
else if (a[x] == 0)
b[x] = " ";
x++;
}

System.out.println("+---+---+---+");
System.out.println("| " + b[0] + " | " + b[1] + " | " + b[2] + " |");
System.out.println("+---+---+---+");
System.out.println("| " + b[3] + " | " + b[4] + " | " + b[5] + " |");
System.out.println("+---+---+---+");
System.out.println("| " + b[6] + " | " + b[7] + " | " + b[8] + " |");
System.out.println("+---+---+---+");

}
}


But out of curiosity and just for educational purposes, I was wondering if there was a more advanced/shorter way of solving this problem? And by shorter I meant writing a smaller code.

You don't need array b. Try this.

    for (int i = 0; i < 9; i += 3) {
System.out.println("+---+---+---+");
for (int j = i; j < i + 3; ++j)
System.out.printf("| %s ", a[j] == 10 ? "O" : a[j] == 100 ? "X" : " ");
System.out.println("|");
}
System.out.println("+---+---+---+");

• I'd also use String.format to improve readability
– Borys Zibrov
Oct 20, 2016 at 20:48
• what does the operand '%s' and '?' mean?
– YRn
Oct 20, 2016 at 20:52
• @YRn See Format String Syntax, and The ? : operator in Java
– saka1029
Oct 20, 2016 at 20:59

You can use the for each loop and switch statement to avoid nested IFs.

public class problem5 {

public static void main(String[] args) {

int[] numbers = { 10, 0, 0, 100, 0, 10, 10, 100, 0 };
String[] b = new String[9];
int x = 0;

for (int number : numbers) {
switch (number) {
case 10:
b[x] = "X";
break;
case 100:
b[x] = "O";
break;
case 0:
b[x] = " ";
break;
}
x++;
}

System.out.println("+---+---+---+");
System.out.println("| " + b[0] + " | " + b[1] + " | " + b[2] + " |");
System.out.println("+---+---+---+");
System.out.println("| " + b[3] + " | " + b[4] + " | " + b[5] + " |");
System.out.println("+---+---+---+");
System.out.println("| " + b[6] + " | " + b[7] + " | " + b[8] + " |");
System.out.println("+---+---+---+");

}
}