【问题标题】:Java: how to access a variable which was declared inside a switch statementJava:如何访问在 switch 语句中声明的变量
【发布时间】:2014-04-26 02:20:32
【问题描述】:

我不确定我这样做是否正确,但我不断收到错误消息,提示我的数组“currentRoute”无法解析为变量。我假设这是因为我在不同的范围内声明了数组。有什么方法可以在我的 switch 语句中声明变量并且仍然使用简单数组的同时让它工作? (我不能使用数组列表,因为我的其余代码会受到影响)

    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]);
    }

还有更多的 switch 语句,但我在这个例子中只包含了 2 个。

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

【问题讨论】:

  • 您已经完成了一些创意代码格式化,但是请理解以无聊的标准方式格式化的代码更容易阅读和理解。
  • 为什么要在switch语句中声明数组?
  • 简答:不。一个变量不能逃脱它被声明的范围。

标签: java arrays scope


【解决方案1】:

这样做

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]);
    }
}

【讨论】:

    【解决方案2】:

    您的案例标签使用花括号定义内部局部范围。 Java 中的一般规则是,当您处于外部范围时,您不能从内部范围访问变量(但是,在内部范围之前定义的外部范围中的变量仍然可见)。因此,无法访问开关内部定义的currentRoute

    解决办法是在开关外定义currentRoute,在开关内做赋值,开关结束后继续访问变量:

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

    请注意,您的代码也有冗余 - 在内部 currentRoute 的两个声明中,您为其分配了一个新数组,然后立即丢弃了该值。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-16
      • 1970-01-01
      • 2017-11-29
      • 2020-12-27
      • 1970-01-01
      • 2021-11-24
      相关资源
      最近更新 更多