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

Categories

0 votes
956 views
in Technique[技术] by (71.8m points)

Handle arithmetic operator in Java

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

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...