我向用户询问一些问题并将答案存储为 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/