Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java:如何访问switch语句中声明的变量_Java_Arrays_Scope - Fatal编程技术网

Java:如何访问switch语句中声明的变量

Java:如何访问switch语句中声明的变量,java,arrays,scope,Java,Arrays,Scope,我不确定我是否做得对,但我一直收到一个错误,说我的数组“currentRoute”无法解析为变量。我假设这是因为我在不同的范围内声明了数组。在switch语句中声明变量并使用简单数组的情况下,有什么方法可以让它工作吗?(我不能使用arraylist,因为我的其余代码将受到影响) 开关(routeID) { 案例“1”:{ String[]currentRoute=新字符串[Route1.length]; currentRoute=Route1; } 案例“96”:{ String[]curren

我不确定我是否做得对,但我一直收到一个错误,说我的数组“currentRoute”无法解析为变量。我假设这是因为我在不同的范围内声明了数组。在switch语句中声明变量并使用简单数组的情况下,有什么方法可以让它工作吗?(我不能使用arraylist,因为我的其余代码将受到影响)

开关(routeID)
{
案例“1”:{
String[]currentRoute=新字符串[Route1.length];
currentRoute=Route1;
}
案例“96”:{
String[]currentRoute=新字符串[Route96.length];
currentRoute=Route96;
}
}
//打印currentRoute中的值
对于(int i=0;i
还有很多switch语句,但我在这个例子中只包含了2个

编辑:switch和for语句都位于同一个方法中。

这样做

String[] currentRoute = null;
switch (routeID)
{
    case "1" : {
        currentRoute = Route1;
    }
    case "96" : {
        currentRoute = Route96;
    }
}

if (currentRoute != null )
    // print out values in currentRoute
    for (int i = 0; i < currentRoute.length; i++)
    {
       System.out.println(currentRoute[i]);
    }
}
String[]currentRoute=null;
交换机(路由器ID)
{
案例“1”:{
currentRoute=Route1;
}
案例“96”:{
currentRoute=Route96;
}
}
如果(currentRoute!=null)
//打印currentRoute中的值
对于(int i=0;i
案例标签使用大括号定义内部局部范围。Java中的一条一般规则是,当您在外部作用域中时,不能从内部作用域访问变量(但是,在内部作用域之前定义的外部作用域中的变量仍然可见)。因此,无法访问交换机内部定义的
currentRoute

解决方案是在交换机外部定义
currentRoute
,在交换机内部进行赋值,并在交换机结束后继续访问变量:

String[] currentRoute;
switch (routeID) {
    case "1" : {
        currentRoute = Route1;
    }
    case "96" : {
        currentRoute = Route96;
    }
    default:
        currentRoute = new String[0];
}
请注意,您的代码也有冗余-在内部
currentRoute
的两个声明中,您为其分配了一个新数组,然后立即丢弃该值


还要注意,我添加了一个默认值。如果没有默认值,Java编译器会抱怨
currentRoute
没有初始化。

您已经进行了一些创造性的代码格式化,但是,请理解,以枯燥的标准方式格式化的代码更易于阅读和理解。为什么要在switch语句中声明数组?简短回答:否。变量不能脱离其声明的范围。
String[] currentRoute;
switch (routeID) {
    case "1" : {
        currentRoute = Route1;
    }
    case "96" : {
        currentRoute = Route96;
    }
    default:
        currentRoute = new String[0];
}