JAVA boolean 变量不会随着Switch语句而改变

标签 java oop boolean

我向用户询问一些问题并将答案存储为 boolean 值(true 或 false)。在我的方法的开头,我将变量声明为:

boolean isWindow = false;

然后使用 switch 语句为我的 boolean 变量分配不同的值:

        answer = INPUT.next().toUpperCase();
        switch (answer) {
        case "Y" : isWindow = true;
        case "N" : isWindow = false;
        }

在尝试将变量分配为“true”后,我使用“System.out.println”来显示变量的值,但它显示为“false”:

        System.out.println("Window: " + isWindow);

如有任何帮助,我们将不胜感激,谢谢。

最佳答案

跌倒。

你忘了打开箱子。

case "Y" : isWindow = true;break;

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

Another point of interest is the break statement. Each break statement terminates the enclosing switch statement. Control flow continues with the first statement following the switch block. The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered.

避免切换的全新想法(假设没有其他情况)

boolean isWindow = INPUT.next().toUpperCase().equals("Y");

关于JAVA boolean 变量不会随着Switch语句而改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47593568/

相关文章:

java - 简单的正则表达式来匹配前导零

asp.net - 对于 HiddenField,Visible 属性有什么用?

java - 改变静态 boolean 值

python - 错误“只能比较相同标记的系列对象”和 sort_index

java - 无法弄清楚如何使用 java cxf 添加 SOAP 头的一部分

java - 通过堆叠各种 block 来 build 最高的塔?

java - 将 java 应用引擎调用转换为 GQL

java - 面向对象设计——暂停功能

design-patterns - 使用类/方法的不同实现的设计模式

c++ - boolean 函数不能正常工作