[英]Why can't I access a variable declared in a switch?
this is my code : there is a probléme "can't acces to variable j" 这是我的代码:有一个问题“不能访问变量j”
public static void main(String args[]) {
char digit = 'a';
for (int i = 0; i < 10; i++){
switch (digit){
case 'x' : { int j = 0; System.out.println(j); }
default : { int j = 100; System.out.println(j); }
}
}
int i = j;
System.out.println(i);
}
Each variable has scope. 每个变量都有作用域。 Scope is a restriction regarding where some variable can be accessed. 范围是在哪里可以访问某些变量的限制。
When you declare a variable in any type of block {}
, that variable can only be accessed within that block of code. 当你在任何类型的块的声明变量{}
该变量只能代码块内访问。
You'll have to declare (and possibly initialize) the variable outside the block so its scope is greater, either at the method level or as a static
variable (or instance if you were working with instance methods). 您必须在块外部声明(并可能初始化)变量,以便在方法级别或作为static
变量(或实例(如果您使用实例方法),则其范围更大)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.