HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavaMinor

Create and print a tic-tac-toe board

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
createtoetictacprintandboard

Problem

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.

Solution

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("+---+---+---+");

Code Snippets

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("+---+---+---+");

Context

StackExchange Code Review Q#144881, answer score: 4

Revisions (0)

No revisions yet.