2 回答
TA贡献1895条经验 获得超7个赞
boolean[] lockers = new boolean[100]; // All are false
boolean be = false;
for (int i = 0; i < lockers.length; i++) {
be = !be;
lockers[i] = be;
if (lockers[i]) {// Or if (be)
System.out.print("o"); // open
} else {
System.out.print("c"); // closed
}
}
System.out.println(); // Write the line out on the console.
Instead: Use:
c == true c
c == false !c (Not operator !)
然后是一些数组索引问题:new boolean[100]传递 100 个布尔值设置为 false,索引为 0 .. 99。
TA贡献1831条经验 获得超9个赞
public static void main(String[] args) {
boolean[] lockers = new boolean[100];
for (int i = 0; i < lockers.length; i++) {
lockers[i] = false;
}
for (int i = 1; i % 2 == 0 && i < lockers.length; i++) {
lockers[i] = true;
}
}
或者
public static void main(String[] args) {
boolean[] lockers = new boolean[100];
for (int i = 0; i < lockers.length; i++) {
lockers[i] = false;
}
for (int i = 0; i < lockers.length; i=i+2) {
lockers[i] = true;
}
}
或者当您只想反转偶数字段的布尔值时
public static void main(String[] args) {
boolean[] lockers = new boolean[100];
for (int i = 0; i < lockers.length; i++) {
lockers[i] = false;
}
for (int i = 0; i < lockers.length; i=i+2) {
lockers[i] = !lockers[i]
}
}
添加回答
举报