小编ggo*_*van的帖子

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

我不确定我是否正确这样做,但我一直收到错误,说我的数组"currentRoute"无法解析为变量.我假设这是因为我已经在不同的范围内声明了数组.有没有什么方法可以让我的工作仍然在我的switch语句中声明变量,同时仍然使用一个简单的数组?(我不能使用arraylist,因为我的其余代码会受到影响)

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

    // print out values in currentRoute
    for (int i = 0; i < currentRoute.length; i++)
    {
        System.out.println(currentRoute[i]);
    }
Run Code Online (Sandbox Code Playgroud)

还有更多的switch语句,但我刚刚为这个例子包含了2个.

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

java arrays scope

2
推荐指数
2
解决办法
1777
查看次数

标签 统计

arrays ×1

java ×1

scope ×1