简体   繁体   English

为什么我不能访问在开关中声明的变量?

[英]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.

相关问题 为什么我不能从Scala访问实现Java接口的类中声明的变量? - Why can't I access a variable declared in a class, which implements a Java interface, from Scala? 为什么不能在switch中使用相同的变量? - Why can't I use same variable in switch? 为什么我不能在Java中的开关内初始化变量? - Why can't I initialize a variable inside a switch in Java? 我在 if 循环之前声明了我的变量,但我无法在循环之外访问它? - I declared my variable before the if-loop but I can't access it outside of the loop? Java帮助:为什么我不能访问当前主方法文件之外的类中声明的静态方法 - Java Help: why can't I access the static methods declared in a class outside the current main method file 为什么我不能使用get方法访问另一个类中声明的TreeMap - Why can't I access TreeMap declared in a class from another with get method foreach:为什么不能在外部声明元素变量? - foreach: why can't the element variable be declared outside? 为什么我无法访问我在开关盒中创建的对象数组 - why i Can't access array of objects which i have created in switch case 为什么我不能以这种方式访问​​ Java 中的受保护变量? - Why can't I access a protected variable in Java this way? 不能影响声明的变量 - Can't affect declared variable
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM