user2777431
user2777431

Reputation: 19

2d boolean array with input values

I have created this code (with the help of Reimeus). How would I achieve to instead of replace every value in the array with true to replace only one pre determined (by z for example) and this always being a value on the top column of the 2d array. Furthermore I would like to how I should start to get instead of the output being true and false it being x for true and y for false but still keeping the array an boolean

import java.util.*;

class Main {
    public static void main(String[] args) {
        int x;
        int y;
        Scanner scanner;
        scanner = new Scanner(System.in);
        x = scanner.nextInt();
        y = scanner.nextInt();
        boolean[][] cells = new boolean[x][y];

        for (int i = 0; i < cells.length; i++) {
            Arrays.fill(cells[i], true);
           System.out.println(Arrays.toString(cells[i]));
        }
    }
}

Upvotes: 0

Views: 2952

Answers (2)

Pshemo
Pshemo

Reputation: 124215

Aside from Reimeus answer:

What would I need to do if I would want to make only 1 piece of the array true and decide where this true should go in the same way as I decide the length of the array.

Using fact that boolean arrays are by default filled with false values you just need to read once index of element that should be set to true just like you did with lengths

boolean[][] cells = new boolean[x][y];

int trueX = scanner.nextInt();
int trueY = scanner.nextInt();
cells[trueX][trueY] = true;

also don't forget to remove Arrays.fill(cells[i], true);


Secondly is there a way in which I could replace the true statement with "*" and the false statement with "-"

You can create second loop that will iterate over elements of row and if it its value is true print * if not - like in this code:

for (int i = 0; i < cells.length; i++) {
    for (int j = 0; j < cells[i].length; j++) {
        if (cells[i][j])
            System.out.print("* ");
        else
            System.out.print("- ");
    }
    System.out.println();
}

or just replace "true" string from result of Arrays.toString() with * and "false" with "-"

for (int i = 0; i < cells.length; i++) {
    System.out.println(Arrays.toString(cells[i]).replace("true", "*")
            .replace("false", "-"));
}

Upvotes: 1

Reimeus
Reimeus

Reputation: 159754

Use Arrays.toString to display the array content, otherwise the Object#toString representation of the Object arrays will be displayed

System.out.println(Arrays.toString(cells[i]));

Upvotes: 1

Related Questions