在switch case java中使用数组

Kai*_*awa 5 java

我有一个代码,其中switch语句测试的依赖于数组变量:

String shuff = Import.shuffle();
String[] form = new String[95];
for(int i = 0; i < 95; i++)
{
    form[i] = Format.shuffle(shuff, i);
}
switch(str)
{
case "a":
    x = 6;
    break;
case "b":
    x = 16; 
    break;
case "c":
    x = 23;
    break;
//So on and so forth
}
Run Code Online (Sandbox Code Playgroud)

我想做的是采用数组形式[]并将其用作案例:

String shuff = Import.shuffle();
String[] form = new String[95];
for(int i = 0; i < 95; i++)
{
    form[i] = Format.shuffle(shuff, i);
}
switch(str)
{
case form[0]:
    x = 6;
    break;
case form[1]:
    x = 16; 
    break;
case form[2]:
    x = 23;
    break;
//So on and so forth
}
Run Code Online (Sandbox Code Playgroud)

但是当我尝试这个时,它会给出错误"case表达式必须是常量表达式".我想到了解决这个问题的两个方案,但我不知道该如何做.1.以某种方式在开关盒中使用数组2.使用某种看起来像这样的方法......

String shuff = Import.shuffle();
String[] form = new String[95];
for(int i = 0; i < 95; i++)
{
    form[i] = Format.shuffle(shuff, i);
}
switch(str)
{
case form[0].toString():
    x = 6;
    break;
case form[1].toString():
    x = 16; 
    break;
case form[2].toString():
    x = 23;
    break;
//So on and so forth
}
Run Code Online (Sandbox Code Playgroud)

还有办法吗?

Import.shuffle方法采用95行(每行为一个字符)的文本文件并将它们串在一起,Format.shuffle将每个原始行放入单独的数组变量中.

我无法将其转换为if else if链,因为它是一个95 case开关(编辑)

Ale*_*ing 5

你不能.Java的switch声明要求case标签是常量表达式.如果您的代码不能使用该限制,则需要使用if...elseif...else构造.

JLS§14.11:

SwitchLabel:
   caseConstantExpression:
   caseEnumConstantName:
   default :

  • @ stealth9799如果您正在认真尝试使用95-case开关,可能有更好的方法来解决这个问题. (2认同)

Fly*_*ter 5

您可以找到str内部索引form,然后根据索引切换.例如:

String shuff = Import.shuffle();
String[] form = new String[95];
for(int i = 0; i < 95; i++)
{
    form[i] = Format.shuffle(shuff, i);
}
int index=Arrays.asList(form).indexOf(str);
switch(index)
{
case 0:
    x = 6;
    break;
case 1:
    x = 16; 
    break;
case 2:
    x = 23;
    break;
//So on and so forth
}
Run Code Online (Sandbox Code Playgroud)

但是,您提出的解决方案都不会起作用,因为在编译代码时,编译器需要确切地知道每个case值是什么,而不仅仅知道它在变量中.我不确定确切的原因,但它可能是为了优化或确保案例不重复(将编译错误,IIRC).底线form[0]是不是常量,编译器想要一个常量.