如果没有大括号的块定义变量时为什么编译错误?

时间:2013-11-28 13:51:28

标签: java javac

为什么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

2 个答案:

答案 0 :(得分:12)

Java不允许你在没有花括号的if语句中定义变量,因为它永远不会被使用(因为它不能被引用的其他行 - 它将超出范围,因此不可用当你点到下一行时。)

如果你在if语句周围放置大括号,它将编译好:

public class Test {
   public static void main(String[] args) {
       if (true) {
           int b = 0;
       }
   }
}

答案 1 :(得分:1)

您需要在中定义变量时添加花括号,如果

public static void main(String[] args) {
    if (true) {
        int b = 0;
    }

}

因为你在没有大括号的情况下写作

if()
//something

如果您尝试定义一个没有任何意义的变量,那么只有该行才能执行。

并且编译器足够聪明地抱怨:)