Reputation: 593
I've just started out on Java and I made a calculator with a GUI which includes this part of code:
private void Decider(char c){
switch (c){
case '+':
CalculatorGui.add.operate();
break;
case '-':
CalculatorGui.sub.operate();
break;`
case '*':
CalculatorGui.mul.operate();
break;
case '/':
CalculatorGui.div.operate();
break;
default:
System.out.printf("Invalid\n");
break;
}
}
The char c
given depends on which button the user clicks on the interface. If he clicks +
we get a +
if he clicks -
we get -
etc. Each time I call the method I need from 4 other classes I've made.
My question is: Is there a way to avoid the switch statement?
I suppose I could make one class with one method and depending on what we pass it will do the proper operation. But then I'll have to make a switch statement in there so this leads nowhere.
Upvotes: 1
Views: 124
Reputation: 124646
You can prepare a map of Runnable
:
Map<Character, Runnable> map = new HashMap<>();
map.put('+', () -> CalculatorGui.add.operate());
map.put('-', () -> CalculatorGui.sub.operate());
map.put('*', () -> CalculatorGui.mul.operate());
map.put('/', () -> CalculatorGui.div.operate());
And then use that map to perform the corresponding action, or the default action:
map.getOrDefault(c, () -> System.out.println("Invalid")).run();
Upvotes: 2