user4833678
user4833678

Reputation:

TicTacToe printing the board

I'm trying to create a game of TicTacToe but would like to ask a question. I have a 2d char array and is filled with underscores - '_' for now. My question is how can I output three underscores per line? Thanks in advance!

import java.util.Scanner;
import java.util.*;
public class TicTacToe {

    public static void main(String[] args){
        Scanner kbd = new Scanner(System.in);

        char[][] theBoard = new char[3][3];

        for(int i = 0; i < theBoard.length; i++){
            for(int j = 0; j < theBoard[i].length; j++){
                theBoard[i][j] = '_';
            }
        }

        for(int i = 0; i < theBoard.length; i++){
            for(int j = 0; j < theBoard[i].length; j++){

                System.out.print(theBoard[i][j] + " ");
            }
        }
    }



}

Upvotes: 1

Views: 93

Answers (3)

jfdoming
jfdoming

Reputation: 975

You can simply do this:

for(int i = 0; i < theBoard.length; i++){
     for(int j = 0; j < theBoard[i].length; j++){
          System.out.print(theBoard[i][j] + " ");
     }
     System.out.println(); // add this
}

In addition, it will probably be faster (slightly) to manually populate your array, rather than use a for loop. e.g

char[][] theBoard = new char[][]{{'_', '_', '_'}, {'_', '_', '_'}, {'_', '_', '_'}};

No need for complex logic when a simple statement will do! :)

Upvotes: 1

Alp
Alp

Reputation: 3105

Modify your code as follows :

    for(int i = 0; i < theBoard.length; i++){
        for(int j = 0; j < theBoard[i].length; j++){

            System.out.print(theBoard[i][j] + " ");
        }
        System.out.println();
    }

That way, you will move to a new line after a row is finished.

__UPDATE__

Another approach would be:

    for(int i = 0; i < theBoard.length; i++){
        StringBuffer buf = new StringBuffer();
        for(int j = 0; j < theBoard[i].length; j++){
            buf.append(theBoard[i][j] + " ");
        }
        System.out.println(buff.toString());
    }

Upvotes: 2

CCV
CCV

Reputation: 19

I believe it's

if ((j + 3) % 3 == 0)

System.out.println()

Upvotes: 0

Related Questions