(非常基础)Java在while循环中设置一个布尔值

时间:2015-04-14 23:54:58

标签: java

主:

public class ElevatorTest {
    public static void main (String []args) {
    Elevator.currentLevel(); // output current level
    Elevator.go(2); // move elevator up 2 floors
    Elevator.currentLevel();
    }
}

类电梯:

public class Elevator {
    public static int currentLevel = 0;
    public static boolean validChoice;

    public static void currentLevel() {
        System.out.println(currentLevel);
    }

    public static void go(int arg) {
        while (validChoice = false) {
            // this building has twenty floors and a basement. 
            // Ground floor is 0 and there are 20 floors above it
            if (-1 < currentLevel + arg && currentLevel + arg < 20) {       
                currentLevel = currentLevel + arg;
                validChoice = true;
            } else {
                System.out.println("You tried to go too high or too 
                                    low. Try again.");
                validChoice = false;
            }
        }
    }
}

在类Elevator的第10行,IntelliJ告诉我布尔validChoice始终为false。如果只满足else语句,我怎样才能让程序将此布尔值设置为false?

3 个答案:

答案 0 :(得分:3)

对于你的while循环while (validChoice = false) {应该有2个等号==来表示比较。

validChoice始终为false的原因是因为您总是将validChoice指定为false。

答案 1 :(得分:1)

在循环之前将validChoice初始化为false并将赋值运算符(=)更改为比较(==)或者只是省略它,因为您正在使用布尔值:

public class Elevator{
public static int currentLevel = 0;
public static boolean validChoice;

public static void currentLevel(){
System.out.println(currentLevel);
}

public static void go(int arg) {
    validChoice = false
    while (!validChoice) {
        if (-1 < currentLevel + arg && currentLevel + arg < 20) {       // this building has twenty floors and a basement. Ground floor is 0 and there are 20 floors above it
            currentLevel = currentLevel + arg;
            validChoice = true;
        } else {
            System.out.println("You tried to go too high or too low. Try again.");
        }
    }
}

我认为你也会遇到一个无限循环的问题,因为在else的情况下,没有办法改变你的arg

答案 2 :(得分:0)

除了提供的其他答案外,请考虑:

while(!validChoice) { 
   ....
}

更自然地读取。