[英]How can I assign Boolean Value true or false to the string “Open” and “Close”
So I have this code but I can't figure out the following: 所以我有这段代码,但我无法弄清楚以下内容:
Why does the output stop at 99? 为什么输出在99处停止? I know I set boolean[100] and I changed it to 101 but that didn't work. 我知道我设置了boolean [100]并将其更改为101,但这没有用。
How can I get the output to print "Locker x is open" or "Locker x is closed"? 如何获得打印“ Locker x is open”或“ Locker x is close”的输出? I know I have to somehow assign boolean true
to open and false
to closed. 我知道我必须以某种方式将布尔值true
分配给open并将false
分配给close。
Please help thanks! 请帮忙谢谢!
public class lockerPuzzle{
public static void main(String[] args){
boolean[] lockers = new boolean[100];
for(int i = 1; i < lockers.length; i++){
for (int j = i; j < lockers.length; j+=i){
if (lockers[j] == false){
lockers[j] = true;
}
else{
lockers[j] = false;
}
}
}
for(int i = 1; i <lockers.length; i++){
System.out.println(lockers[i] + " " + i);
}
}
}
You started at index 1, when you should have started at index 0. 您应该从索引1开始,而应该从索引0开始。
1-99 (99 elements) 1-99(99个元素)
0-99 (100 elements) 0-99(100个元素)
public static void main(String[] args){
boolean[] lockers = new boolean[100];
for(int i = 0; i < lockers.length; i++){
for (int j = i; j < lockers.length; j+=i){
if (lockers[j] == false){
lockers[j] = true;
}
else{
lockers[j] = false;
}
}
}
for(int i = 0; i <lockers.length; i++){
System.out.println(lockers[i] + " " + i);
}
}
You can check the truth value of the boolean and print some text based on its value: 您可以检查布尔值的真值并根据其值打印一些文本:
public class lockerPuzzle{
public static void main(String[] args){
// ...
for(int i = 0; i < lockers.length; i++){
boolean isOpened = lockers[i]
if (isOpened) {
System.out.println("Locker " + i + " is opened!");
} else {
System.out.println("Locker " + i + " is closed!");
}
}
}
}
Note: This can be much more concise using more variables or ternary operators, but this will do for a new programmer. 注意:使用更多变量或三元运算符可以使此操作更为简洁,但这对于新程序员来说确实如此。 Good luck. 祝好运。
You are starting index from 1, Which will skip the first item in the Array. 您将从1开始索引,它将跳过数组中的第一项。 I have simplified your code here is the code, You don't really need those if statements 我简化了您的代码,这里是代码,您实际上并不需要那些if语句
public static void main(String[] args){
boolean[] lockers = new boolean[100];
for(int i = 0; i < lockers.length; i++){
for (int j = i; j < lockers.length; j+=i){
lockers[j] = !lockers[j];
}
}
for(int i = 1; i <lockers.length; i++){
System.out.println(lockers[i] + " " + i);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.