gpt4 book ai didi

java - 在 Java 开关中声明和初始化变量

转载 作者:IT老高 更新时间:2023-10-28 11:32:28 25 4
gpt4 key购买 nike

我有一个关于 Java 开关的疯狂问题。

int key = 2;

switch (key) {
case 1:
int value = 1;
break;
case 2:
value = 2;
System.out.println(value);
break;
default:
break;
}

场景 1 - 当 key 为 2 时,它成功将值打印为 2。
场景 2 - 当我要在 case 2: 中评论 value = 2 时,它会大声说 局部变量值可能不是初始化

问题:

场景1:如果执行流程不去case 1:(当key = 2时),那它怎么知道值变量的类型为 int

场景2:如果编译器知道value变量的类型为int,那么它一定已经访问到int value = 1; case 1 中的表达式:.(声明和初始化)。那为什么会发出吱吱声当我要在case 2:中注释value = 2时,说局部变量值可能没有被初始化

最佳答案

基本上,Switch 语句的作用域很奇怪。来自 section 6.3 of the JLS :

The scope of a local variable declaration in a block (§14.4) is the rest of the block in which the declaration appears, starting with its own initializer and including any further declarators to the right in the local variable declaration statement.

在您的情况下, case 2case 1 位于同一 block 并出现在它之后,即使 case 1 永远不会执行......所以局部变量在范围内并且可用于写入,尽管您在逻辑上从不“执行”声明。 (虽然初始化是,但声明并不是真正的“可执行”。)

如果你注释掉 value = 2; 赋值,编译器仍然知道你指的是哪个变量,但你不会经历任何为其赋值的执行路径,这就是为什么当您尝试读取任何其他未明确分配的局部变量时会出现错误的原因。

我强烈建议您不要使用在其他情况下声明的局部变量 - 正如您所见,这会导致代码高度困惑。当我在 switch 语句中引入局部变量时(我很少尝试这样做 - 理想情况下,案例应该很短)我通常更喜欢引入一个新的范围:

case 1: {
int value = 1;
...
break;
}
case 2: {
int value = 2;
...
break;
}

我相信这更清楚。

关于java - 在 Java 开关中声明和初始化变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10810768/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com