我已经创建了这段代码(在Reimeus的帮助下)。我将如何实现而不是用true替换数组中的每个值,而只替换一个预先确定的(例如z),并且这总是在2d数组的顶部列上的值。此外,我想我应该如何开始获取而不是输出为真和假它是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]));
}
}
}
答案 0 :(得分:1)
使用Arrays.toString
显示数组内容,否则将显示Object#toString
数组的Object
表示
System.out.println(Arrays.toString(cells[i]));
答案 1 :(得分:1)
除了Reimeus回答:
如果我只想让数组的1个为真,那么我需要做什么才能确定应该采用与确定数组长度相同的方式。
使用boolean
数组默认填充false
值的事实,您只需读取一次应设置为true
的元素索引,就像使用{{1}一样}}Š
length
也不要忘记删除boolean[][] cells = new boolean[x][y];
int trueX = scanner.nextInt();
int trueY = scanner.nextInt();
cells[trueX][trueY] = true;
其次有一种方法可以用“*”替换真实的语句,用“ - ”替换错误的语句
您可以创建第二个循环来迭代行的元素,如果它的值为Arrays.fill(cells[i], true);
,则打印true
如果不是*
,则在此代码中如下:
-
或只是将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();
}
字符串替换为带有"true"
的Arrays.toString()和带有*
的{{1}}的结果
"false"