【发布时间】: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语句中声明数组?
-
简答:不。一个变量不能逃脱它被声明的范围。