Java中的范围规则 [英] Scoping rules in Java

查看:116
本文介绍了Java中的范围规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮我理解Java中的范围规则吗?这显然无效:

Can someone help me understand the scoping rules in Java? This is clearly not valid:

    {
        int i = 0;
        System.out.println(i); // fine, of course
    }
    System.out.println(i); // syntax error

i {} ,它在外面不可用。那么这个怎么样:

i is declared within the {}, and it's not available outside. So what about this:

    for (int i = 0; i < 10; i++) {
         System.out.println(i); // fine, of course
    }
    System.out.println(i);  // syntax error, same as above.

我对此处的语法错误感到惊讶。 i 在外部范围内声明,但稍后无法使用。是否通过的某些特殊规则为循环绑定到内部块范围?还有其他可能发生这种情况的情况吗?

I'm surprised at the syntax error here. i is declared in the outer scope yet it is not available later on. Is it bound to the inner block scope by some special rule for for loops? Are there other scenarios where this can happen?

推荐答案

想到for循环实际上代表如下:

think of for loop actually represented like this:

{
  int i = 0;
  while (i < 10) {
    // your code
    i ++
  }
}

这篇关于Java中的范围规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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