为什么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;
}
}
}
关于java - 为什么在不带大括号的情况下定义变量时会出现编译器错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20267906/