First Split the string and store the operator in the Character variable. You can use split()
to split a String and assign it to a String array. Access operator using the array index and assign it to a Character variable.
Now You can use Map
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 map = new HashMap<>();
map.put('+', plusObject);
map.put('-', minusObject);
map.put('*', multiplyObject);
map.put('/', divideObject);
To get the object type of operator, you can use map.get(character)
it will return the object according to the character and null otherwise.
Update: Create four classes and a object for each class namely plusObject
, minusObject
, multiplyObject
,divideObject
. These are the objects that you add to HashMap
initially. Have a evaluate()
function in each class. Now with the returned object, call the evaluate()
method which will make call to respective class. You need not check the Object
type using any conditional statements.