英文:
I dont understand why this code with switch statement dont gives a compilation error or throw an runtime exception
问题
int param1 = 1;
switch (param1){
case 0:
int block2 = 10; // 如果注释掉这行会导致编译错误
System.out.println(block2);
break;
case 1:
block2 = 5; // 如果注释掉这行,下面的行会导致编译错误
System.out.println(block2);
break;
default:
// System.out.println(block2); // 编译错误
}
我尝试调试,但不合理,因为我看不到变量的声明。此代码在主函数中运行。
英文:
int param1 = 1;
switch (param1){
case 0:
int block2 = 10; // if this line is commented gives a compilation error
System.out.println(block2);
break;
case 1:
block2 = 5; // if this line is commented below line gives a compilation error
System.out.println(block2);
break;
default:
// System.out.println(block2); // comilation error
}
I try debug and dont makes sence because I dont see the declaration of the variable. this code run in a main
答案1
得分: 1
这是关于 switch
表达式的一个特殊情况。Java编译器允许你声明变量,并在它被初始化后引用它。这就是为什么你需要对它赋值的原因,所以你的情况 2
会导致编译错误:它看到了从情况 0
中的声明,但没有初始化,所以你不能引用它。
然而,这段代码很令人困惑,你不应该这样写。每个 case
使用不同的变量名称。像IntelliJ这样的IDE会在你这样做时生成警告:
在一个
switch
分支中声明的本地变量 'block2' 被在另一个分支中使用。
英文:
It's a quirk of switch
expressions. The Java compiler allows you to declare the variable, and to reference it if it has been initialized. That's why you need to assign it, so why your case 2
gives a compilation error: It sees the declaration from case 0
, but there's no initialization, so you can't reference it.
However, this code is confusing, and you shouldn't write it like this. Use a different variable for each case
. An IDE like IntelliJ will generate a warning if you do it this way:
> Local variable 'block2' declared in one 'switch' branch and used in another
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论