For循环,切换布尔值

我正在尝试创建一个 for 循环并在每个循环中切换布尔值。

首先,我做了一系列100储物柜,每个人都关着。

然后,在第一个循环中,我想打开所有的储物柜,然后改变每隔一个储物柜的状态(2,4,6...等),依此类推,直到最后,它只改变100th储物柜 的状态。


因此,如果它的假(锁定)它应该更改为真,如果它的真(打开)相反。问题是,我不完全确定如何更改状态,我期待您的帮助。


请提出任何解决方案


    public static void main(String[] args) {

    boolean[] lockers = new boolean[101];

    for (int i = 1; i < lockers.length; i++) {

        lockers[i] = false; 

        }

    for (int i = 1; i < lockers.length; i++) {

        lockers[i+i] = lockers[i+i] == true ? false : true;

        if(lockers[i] == true)

            System.out.print("o"); //open

        if(lockers[i] == false) {

            System.out.print("c"); //closed

            }

        }

    }

}


守着一只汪
浏览 107回答 2
2回答

人到中年有点甜

boolean[] lockers = new boolean[100]; // All are falseboolean be = false;for (int i = 0; i < lockers.length; i++) {&nbsp; &nbsp; be = !be;&nbsp; &nbsp; lockers[i] = be;&nbsp; &nbsp; if (lockers[i]) {// Or if (be)&nbsp; &nbsp; &nbsp; &nbsp; System.out.print("o"); // open&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; System.out.print("c"); // closed&nbsp; &nbsp; }}System.out.println(); // Write the line out on the console.Instead:&nbsp; &nbsp; &nbsp; Use:c == true&nbsp; &nbsp; &nbsp;cc == false&nbsp; &nbsp; !c&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;(Not operator !)然后是一些数组索引问题:new boolean[100]传递 100 个布尔值设置为 false,索引为 0 .. 99。

天涯尽头无女友

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; lockers[i] = false;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; for (int i = 1; i % 2 == 0 && i < lockers.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; lockers[i] = true;&nbsp; &nbsp; }}或者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; lockers[i] = false;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; for (int i = 0; i < lockers.length; i=i+2) {&nbsp; &nbsp; &nbsp; &nbsp; lockers[i] = true;&nbsp; &nbsp; }}或者当您只想反转偶数字段的布尔值时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; lockers[i] = false;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; for (int i = 0; i < lockers.length; i=i+2) {&nbsp; &nbsp; &nbsp; &nbsp; lockers[i] = !lockers[i]&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java