I tried to evaluate an expression using two stacks (operands stack and operators stack). For now I just want to test my program with addition and subtraction but it keeps return 0, I guess it didn't do math right. Please help
public static void main(String[] args) {
int userChoice;
String expression;
int finalresult;
Scanner keyboard = new Scanner(System.in);
System.out.println(" 1. Keyboard");
System.out.println(" 2. From a file");
System.out.println();
System.out.print("Select (1), (2): ");
// Integer Stack that is used to store the integer operands
GenericStack<Integer> stackForOperands = new GenericStack<Integer>();
// Character Stack that is used to store the operators
GenericStack<Character> stackForOperators = new GenericStack<Character>();
userChoice = keyboard.nextInt();
switch (userChoice) {
case 1:
System.out.print("Please enter an expression seperated by space: ");
keyboard.nextLine();
expression = keyboard.nextLine();
String[] tokens = expression.split("\\s+");
for (int i = 0; i < tokens.length; i++) {
if (tokens[i].matches("-?\\d+")) {
stackForOperands.push(Integer.parseInt(tokens[i]));
} else {
if (tokens[i] == "+" || tokens[i] == "-") {// if the extracted item is a + or – operator
if (stackForOperators.isEmpty())
stackForOperators.push(tokens[i].charAt(0));
else {
if (tokens[i] == "*" || tokens[i] == "/")
stackForOperators.push(tokens[i].charAt(0));
//else
// int top = stackForOperators.getTop();
// while (top != -1) {
//oneOperatorProcess(stackForOperands, stackForOperators);
// top = top - 1;
// }
}
}// end of checking "+", "-"
}
}
oneOperatorProcess(stackForOperands, stackForOperators);
finalresult = stackForOperands.pop();
System.out.println(finalresult);
}
}
My method to perform operation
public static void oneOperatorProcess(GenericStack val, GenericStack op) {
char operator = (char) op.getTop();
int a = (int) val.pop();
int b = (int) val.pop();
int result = 0;
switch (operator) {
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
result = a / b;
break;
default:
//return 0;
}
val.push((int) result);
//return result;