在for循环中声明的变量的范围 [英] Scope of variable declared in for loop

查看:126
本文介绍了在for循环中声明的变量的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我解释一下。

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

I have a int i = 9 inside main method. Now i have for loop inside same main method.Look the following example

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 above example it is showing compile time error that i is already defined.From this error i think that scope of i declared in for condition is also outside loop.

现在看下面的例子

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的循环外的错误。

In above example it is showing error outside for loop that cannot find symbol i.

如果找不到我在for循环条件中声明。那么为什么呢显示i已在第一个示例中定义

推荐答案

根据阻止


块是平衡大括号之间的一组零个或多个语句,可以在允许单个语句的任何地方使用。

A block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed.

所以

{   //block started

}    //block ended

什么变量声明在块内部,范围仅限于该块。

What ever the variables declared inside the block ,the scope restricted to that block.

拇指规则的变量范围是 {}

A thumb rule will be scope of variable is with in {}.

public static void main(String... args) throws Exception{   
    int i =39;
    for (int i = 0; i < 10; i++) {   
     System.out.println(i); // which i ?? 
    }
  }

在上述情况下,编译器会混淆它正在寻找,因为 i 已经定义,并且它还有一个可以循环访问的范围。

In the above case the compiler confuses which i it's looking for since the i already defined and it have a scope to access in loop also.

方法范围中已定义 i

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

    for (int i = 0; i < 10; i++) {
    }
    System.out.println(i); // the scope ended already with in {}
  }

在上述情况下 i 范围已在{$ 的中结束,且外部不可用。

In above case the i scope already ended in for {} ,and outside not available.

这篇关于在for循环中声明的变量的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆