Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have four classes for handling math operations: Plus, Multiply, Divide, Minus

my input is like this:

1, 2, +

Now my question is this : How can we determine the type of operator then call the correct class?(implement without if-else or switch-case)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
960 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use Map<Character,Object> where you can store character and object to calculate in single structure and access later with character only without any if-else or switch.

Map<Character,Object> map = new HashMap<>();
map.put('+', plusObject);
map.put('-', minusObject);
map.put('*', multiplyObject);
map.put('/', divideObject);

Now my question is this : How can we determine the type of operator then call the correct class?

map.get(character) it will return the object according to the character and null otherwise.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...