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.

JavaScript

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:

JavaScript

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:

JavaScript

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

JavaScript

then you can use for loop

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement