0

我已经创建了这段代码(在 Reimeus 的帮助下)。我将如何实现而不是将数组中的每个值替换为 true 以仅替换一个预先确定的值(例如由 z 确定),并且这始终是二维数组顶列上的值。此外,我想知道我应该如何开始获取,而不是输出为真和假,它是 x 代表真,y 代表假,但仍然保持数组为布尔值

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]));
        }
    }
}
4

2 回答 2

1

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", "-"));
}
于 2013-09-13T18:23:18.513 回答
1

用于Arrays.toString显示数组内容,否则会显示数组的Object#toString表示Object

System.out.println(Arrays.toString(cells[i]));
于 2013-09-13T18:00:22.997 回答