树上说这么写是错的?
{
int x = 12;
{
int x = 96; // Illegal
}
}
但是为什么如下又是正确的啊?
public class Qqq{
public static void main(String args[])
{
{
int x=10;
}
int x=100;
}
};
{
int x = 12;
{
int x = 96; // Illegal
}
}
但是为什么如下又是正确的啊?
public class Qqq{
public static void main(String args[])
{
{
int x=10;
}
int x=100;
}
};
和第2个例子不是一样的嘛?为什么第2个例子就可以正常运行
public static void main(String args[])
{
{
int x=10;
System.out.println(x);
}
int x=100;
System.out.println(x);
}
}; 楼主看的书可能误导你,建议换本,没错的
{
int x = 12;
{
int x = 96; // Illegal
}
}原因:在外面的块中声明了 x, 此 x 是一个局部变量,且在里面的块中也是有效的。
又在里面的块中声明 x, 此 x 因为与前个局部变量重名,
所以会报重复声明局部变量错误。这个是正确的:
public static void main(String[] args) {
{
int x=10; //(1)
System.out.println(x);
} //(2)
int x=100; //(3)
System.out.println(x);
}原因:
在(1)处声明的局部变量x 只是块中有效,到了(2)的时候x 也就没有影响了。
此时再执行(3)语句就不会出现重复声明局部变量的错误。同理,你把(3)这一行调到main()中的第一行,也会出现前面那个一样的错误。
int x = 12; //在前
{
int x = 96; // Illegal //局部
}
} 注意一下层次,和前后
{
{
int x=10;
}
int x=100; //在后
}