首页 > 解决方案 > 使用在 if 语句中更改的变量

问题描述

我正在用 JAVA 编写一个程序,我需要更改一个布尔值,但我无法修复它。

布置如下

while(statement){
    Boolean behind = true;

    if (behind == true){
        do something
        behind = false;
        } 

    if (behind == false){
        do something else
        behind = true;
        }
}

所以基本上我的程序需要迭代“做某事”和“做其他事情”。但我认为我的布尔值behind不会被 if 语句改变,因为那个“版本”behind只存在于语句中。有关如何应对此问题的任何建议?

标签: javaif-statementvariablesbooleanglobal-variables

解决方案


Boolean behind = true;
while(statement){
    if (behind){
        do something;
        behind = false;
    }else{
        do something else;
        behind = true;
     } 
}

推荐阅读