I need to get rid of if, else statements from my code as it is a smell. I know you can implement the state pattern to get rid of them, however in my code I'm checking if the string input is a certain operator and then doing things on a stack. How would I go about this? Should I make different states which do the maths and the stack operations as well? My main problem is I don't understand how to implement it without using a if statement, for example if I encounter a operator I want to do something, but as theres a number of different operators so I need to check that the input is a "+" to carry out the code required for that section.
Heres my code:
package src;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;
public class RPNCalculator {
public int solveEquation(final String input) {
final Stack<Integer> operands = new Stack<Integer>();
List<String> tokenizedInput = Arrays.asList(input.split(" "));
for (String currentToken : tokenizedInput) {
try {
int inputAsInt = Integer.parseInt(currentToken);
operands.push(inputAsInt);
continue; //
} catch (NumberFormatException exception) {
}
if (currentToken.contains("+")) {
int total = operands.pop() + operands.pop();
operands.push(total);
} else if (currentToken.contains("-")) {
int secondNum = operands.pop();
int total = operands.pop() - secondNum;
operands.push(total);
} else if (currentToken.contains("*")) {
int total = operands.pop() * operands.pop();
operands.push(total);
} else if (currentToken.contains("/")) {
int secondNum = operands.pop();
int total = operands.pop() / secondNum;
operands.push(total);
}
try/continue/catchblock., That took me far too long to decipher. Theif/else's simply contain a lot of duplicated/inconsistent code and that code could be improved. But testing via that series of if's isn't a smell in itself.