有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

for循环中声明的变量的java作用域

让我解释一下疑问

我在main方法中有一个int i = 9。现在我有了相同的主方法中的for循环。看下面的例子

class Test {

  public static void main(String... args) throws Exception{   
    int i =39;
    for (int i = 0; i < 10; i++) {   // error:i already defined
    }
  }

}

在上面的例子中,它显示了我已经定义的编译时错误。根据这个错误,我认为我在for条件中声明的范围也在循环之外

现在看看下面的例子

class Test {

  public static void main(String... args) throws Exception{   

    for (int i = 0; i < 10; i++) {
    }
    System.out.println(i); // error: cannot find symbol i
  }

}

在上面的示例中,它显示了找不到符号i的循环外部的错误

如果没有找到,我在for循环条件中声明。那么为什么它显示i已经在第一个示例中定义了


共 (2) 个答案

  1. # 1 楼答案

    在这个例子中

    class Test {
    
      public static void main(String... args) throws Exception{   
        int i =39;
        for (int i = 0; i < 10; i++) {   // error:i already defined
        }
      }
    
    }
    

    您将i声明为int2次,这在java中是不允许的,因为它们在同一范围内

    在这个例子中

    class Test {
    
      public static void main(String... args) throws Exception{   
    
        for (int i = 0; i < 10; i++) {
        }
        System.out.println(i); // error: cannot find symbol i
      }
    
    }
    

    i的作用域在for循环中,您试图在for循环外打印i

    这是工作代码

    class Test {
    
      public static void main(String... args) throws Exception{   
        int i;
            for ( i = 0; i < 10; i++) {
            }
            System.out.println(i); // error: cannot find symbol i
          }
    
    }
    

    输出10

  2. # 2 楼答案

    第一个例子: i范围是整个main方法

    第二个例子: i作用域是for循环

    干杯