![](/img/trans.png)
[英]Compiler error when declaring a variable inside if condition and no curly braces
[英]Why compiler error when defining a variable if block without braces?
为什么Java编译器在以下代码中建议语法错误?
1 public class Test {
2 public static void main(String[] args) {
3 if (true)
4 int b = 0;
5 }
6 }
Test.java:4: '.class' expected
int b = 0;
^
Test.java:4: not a statement
int b = 0;
^
Test.java:4: illegal start of expression
int b = 0;
^
Test.java:4: ';' expected
int b = 0;
^
4 errors
Java不允许你在没有花括号的if语句中定义变量,因为它永远不会被使用(因为它不能被引用的其他行 - 它将超出范围,因此一旦你不可用点击下一行。)
如果你在if语句周围放置大括号,它将编译正常:
public class Test {
public static void main(String[] args) {
if (true) {
int b = 0;
}
}
}
在if中定义变量时需要添加花括号。
public static void main(String[] args) {
if (true) {
int b = 0;
}
}
因为你写的时候没有花括号
if()
//something
如果您尝试定义一个没有任何意义的变量,那么只有该行才会执行。
并且编译器足够聪明地抱怨:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.