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

Time:12-28

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.

CodePudding user response:

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();
   }
}

CodePudding user response:

switch-statements and switch-expressions are useful when you need to define multiple execution paths depending on the value of a single variable (for more information, refer to the official tutorial), but in your can cause you need to operate with multiple variables.

As a possible solution, you can collect these variable into an array or a List, and then check if it contains a value of 1.

Example:

List<Integer> vars = List.of(var1, var2, var3, ... );
...
if (vars.contains(1)) { ... }

CodePudding user response:

i prefer to use HashMap because the complexity is o(1), so you can get it directly by using the constant key, for ex:

private final int KEY = 1; 
Map<Integer, Integer> testMap = new HashMap<>();
// populate testMap

Integer result = testMap.get(KEY);

CodePudding user response:

def search(value): var1 = 'apple'

var2 = 'banana' var3 = 'cherry'

if found: print(f'{value} was found!') else: print(f'{value} was not found.')

search('apple')
search('orange')

CodePudding user response:

You can use the functional programming approach in Java to iterate over a given set of items. for example:

Set<Integer> set = new HashSet<>();
        set.add(1);
        set.add(2);
        set.add(3);
//adding items to this set for demonstration purposes. In your case the given Set is already populated
        Set<Integer> filteredSet = set.stream().filter(item -> item == 1).collect(Collectors.toSet());
        filteredSet.forEach(item -> {
            System.out.println("Item: "  item);
        });

Explanation: set.stream() opens a Stream for the given Items in this set.
stream().filter(x -> x == 1) filteres all items, which are not applying to the given filter-function "x -> x == 1".
This filter-function essentially defines an "item" which then can be compared to the value of 1 through the "equals"-Operator. The method "collect(Collectors.toSet())" takes all the filtered items (in this case its only the Integer of the value 1) and assigns those values to the new Set "filteredSet". After that the given filteredSet is being iterated over via the functional Method "forEach()" which then prints all values of the given Set. (in this case only 1 value of "1")

  • Related