如何将布尔值 true 或 false 分配给字符串“打开”和“关闭”

所以我有这个代码,但我无法弄清楚以下内容:

  1. 为什么输出停止在 99?我知道我设置了 boolean[100] 并将其更改为 101 但这不起作用。

  2. 如何让输出打印“Locker x 已打开”或“Locker x 已关闭”?我知道我必须以某种方式分配布尔值true来打开和false关闭。

请帮忙谢谢!

代码

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);

        }

    }

}



陪伴而非守候
浏览 202回答 2
2回答

神不在的星期二

为什么输出停止在 99?您从索引 1 开始,而您应该从索引 0 开始。区别1-99 (99 元素)0-99(100 个元素)代码public static void main(String[] args){&nbsp; &nbsp; boolean[] lockers = new boolean[100];&nbsp; &nbsp; for(int i = 0; i < lockers.length; i++){&nbsp; &nbsp; &nbsp; &nbsp; for (int j = i; j < lockers.length; j+=i){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (lockers[j] == false){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; lockers[j] = true;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; lockers[j] = false;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; for(int i = 0; i <lockers.length; i++){&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(lockers[i] + " " + i);&nbsp; &nbsp; }}如何获得打印 Locker x is open 或 closed 的输出?您可以检查布尔值的真值并根据其值打印一些文本:public class lockerPuzzle{&nbsp; &nbsp; public static void main(String[] args){&nbsp; &nbsp; &nbsp; &nbsp; // ...&nbsp; &nbsp; &nbsp; &nbsp; for(int i = 0; i < lockers.length; i++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; boolean isOpened = lockers[i]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (isOpened) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Locker " + i + " is opened!");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Locker " + i + " is closed!");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}注意:这可以使用更多变量或三元运算符更简洁,但这对新程序员有用。祝你好运。

呼唤远方

您从 1 开始索引,这将跳过数组中的第一项。我已经简化了你的代码,这里是代码,你真的不需要那些 if 语句public static void main(String[] args){&nbsp; &nbsp; boolean[] lockers = new boolean[100];&nbsp; &nbsp; for(int i = 0; i < lockers.length; i++){&nbsp; &nbsp; &nbsp; &nbsp; for (int j = i; j < lockers.length; j+=i){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; lockers[j] = !lockers[j];&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; for(int i = 1; i <lockers.length; i++){&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(lockers[i] + " " + i);&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java