Skip to content
Advertisement

Is there a way to search for a value from an assortment of variables using a switch statement?

I am a novice in java, and I am trying to make a search-algorithm for this situation.

I’m attempting to search through a set of 12 integers to find a value equal to 1, similar to this long if-else chain.

if (var1 == 1){
    break;
} else if (var2 == 1){
    break;
} else if (var3 == 1){
    break;
} else if (var4 == 1){
    break;
} else if (var5 == 1){
    break;
} else if (var6 == 1){
    break;
} else if (var7 == 1){
    break;
} else if (var8 == 1){
    break;
} else if (var9 == 1){
    break;
} else if (var10 == 1){
    break;
} else if (var11 == 1){
    break;
} else if (var12 == 1){
    break;
}

However, in an attempt to clean up the code and learn new technique, I am attempting to employ a switch statement to search these variables instead.

The problem I am encountering is that, in order to compare my variables to the constant (1), I feel like I need to use a boolean as the case condition:

switch (){
   case var1 == 1: break;
}

However, this throws two errors: there is no expression for the switch statement, and the case condition is a boolean (it expects an int).

The other problem that I’ve seen is that the case condition must be a constant, meaning I can’t have it as a variable:

switch (1){
   case var1: break;
}

I think this would trigger if this syntax was correct, but I can’t figure out any other ways to do it without using arrays, which I don’t really understand.

Advertisement

Answer

you need to create an array for your variables such as

const vars = {1, 2, 3, .. etc}

then you can use for loop

for(let i=0; i<vars.length; i++){
   if(vars[i] == 1){
      // things you want to do
      break();
   }
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement