0

I wonder if it's possible to fill a multidimensional boolean Array with a string.

Let's imagine we are making Battleship Game something like:

public static void main(String[] args) {
    boolean[][] board = new boolean[5][5];

    board[3][2] = true;
    board[0][0] = true;

    for (boolean[] line : board
         ) {
        System.out.println(Arrays.toString(line));
    }

}

Now is it possible to change all the Values to be " [ ] " if its false and to be " [X] " if its true but still keep the boolean values?

6
  • Use an inner loop and if statements...You can't change the values of the boolean array to Strings but you can print Strings instead of boolean values. Commented Feb 16, 2016 at 16:12
  • 1
    "if boolean array true then fill it with a String" - No. A boolean array can hold only booleans. Commented Feb 16, 2016 at 16:12
  • Well you can always do a replaceAll("true", "[X]").replaceAll("false", "[ ]") on output string. Commented Feb 16, 2016 at 16:13
  • @DawidPura Why replaceAll and not simply replace? Commented Feb 16, 2016 at 16:16
  • I think u r misleading because of some other language concepts like C or any but don't forget this is java where Boolean only accepts either "true" or "false" neither a string ,char or int.. But u may get help of any collection class.. I am sure u will got d solution. Thanks Commented Feb 16, 2016 at 16:20

1 Answer 1

4

The most obvious solutrion is to use an Object instead of a boolean. You can then override it's toString method.

class Square {

    private boolean taken;

    public boolean getTaken() {
        return taken;
    }

    public void setTaken(boolean taken) {
        this.taken = taken;
    }

    @Override
    public String toString() {
        return taken ? "X" : " ";
    }

}

public void test() {
    Square[][] board = new Square[5][5];
}

And who knows where that will lead - perhaps even (gasp) a Board object!

class Board {

    Square[][] board = new Square[5][5];

    public Board() {
        for (Square[] row : board) {
            for (int j = 0; j < row.length; j++) {
                row[j] = new Square();
            }
        }
    }

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.