gpt4 book ai didi

java - for 循环中声明的变量范围

转载 作者:行者123 更新时间:2023-12-02 07:01:12 25 4
gpt4 key购买 nike

疑惑解释一下

我在 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
}
}

}

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

现在看下面的例子

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
}

}

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

如果它没有找到在 for 循环条件中声明的 i。那么它显示 i 的原因已经在第一个示例中定义

最佳答案

根据 Block 的定义

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

无论在 block 内声明什么变量,范围都限制在该 block 内。

经验法则是变量的范围在 {} 中。

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,因为 i 已经定义并且它也有一个循环访问的范围。

main 方法范围内已经定义了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 范围已经在 for {} 中结束,并且外部不可用。

关于java - for 循环中声明的变量范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20542569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com