Using arrays in java switch enclosure

I have code in which what the switch statement is testing depends on an array variable:

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
}

What I want to do is take the form of the array [] and use it as an example:

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
}

But when I try to do this, it gives the error "case expressions must be constant expressions." Two solutions come to mind, but I do not know how to do it. 1. Use an array in the switch case somehow 2. use some method that will look like this ...

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
}

Is there any way to do this?

The Import.shuffle method accepts a text file with 95 lines (each line is a single character) and concatenates them together, and Format.shuffle puts each of the source lines in separate array variables.

if else if, 95- (edit)

+4
4

. Java switch , case . , if...elseif...else.

. §14.11 JLS:

SwitchLabel :
    case ConstantExpression :
    case EnumConstantName :
    default :

+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
}

, , , , case, , . , , , ( , IIRC). , form[0] , .

+4

, Java switch.

, . , x . , x Map, int, ( O(1) ).

:

//With maps - based on string values
Map<String, Integer> values = new HashMap<String, Integer>();
values.put(form[0], 6);
values.put(form[1], 16);
values.put(form[2], 23);
//....
x = (int) values.GetValue(str); //str value is your indexer here.


//With arrays, based on indexes
int[] values = new int[] {6, 16, 23/*,...*/};
x = values[i]; // i is your indexer here.
+3

, if/else. , , . :

if      (str.equals(form[0])) { x = 6; }
else if (str.equals(form[1])) { x = 16; }
else if (str.equals(form[2])) { x = 23; }

.

0

Source: https://habr.com/ru/post/1568491/


All Articles