gpt4 book ai didi

java - java中for语句中删除括号与添加括号有什么区别

转载 作者:行者123 更新时间:2023-11-30 07:42:18 25 4
gpt4 key购买 nike

我在我的项目中尝试了以下代码。

import java.util.*;
public class Test{
public static void main(String [] args){
for(int i=0;i<=10;i++)
Integer k = new Integer(i);//ERROR
System.out.println("Hello Word");
}
}

但是,由于这一行,该代码片段无法编译:整数 k = new Integer(i);

和更改自

Integer k = new Integer(i);

{Integer k = new Integer(i);}

这个片段没问题

我的问题:

我的代码片段下的 Integer k = new Integer(i);{Integer k = new Integer(i);} 有什么区别?

谢谢

最佳答案

请参阅this answer

每次循环时,您的初始声明都会超出范围,从而使其无用。

方括号创建一个新范围。

范围定义

Scope refers to the lifetime and accessibility of a variable. How large the scope is depends on where a variable is declared. For example, if a variable is declared at the top of a class then it will accessible to all of the class methods. If it’s declared in a method then it can only be used in that method.

Here是范围和范围外的一个很好的例子

// Demonstrate block scope.
class Scope {
public static void main(String args[])
{
int n1; // Visible in main

n1 = 10;

if(n1 == 10)
{
// start new scope
int n2 = 20; // visible only to this block

// num1 and num2 both visible here.
System.out.println("n1 and n2 : "+ n1 +""+ n2);
}
// n2 = 100; // Error! y not known here

// n1 is still visible here.
System.out.println("n1 is " + n1);
}
}

关于java - java中for语句中删除括号与添加括号有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34478829/

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