publicbooleanisFull() { return top == maxSize - 1; }
publicbooleanisEmpty() { return top == -1; }
//push publicvoidpush(int value) { if (isFull()) { System.out.println("The stack has been full. Can't push new value in it."); return; } top++; stack[top] = value; }
//pop publicintpop() { if (isEmpty()) { thrownewRuntimeException("The stack has been empty. Can't pop."); }
intvalue= stack[top]; top--; return value; }
//peek publicintpeek() { return stack[top]; }
//iterate (from top to bottom) publicvoidshowStack() { if (isEmpty()) { System.out.println("The stack is empty."); return; }
for (inti= top; i >= 0; i--) { System.out.println("stack[" + i + "] = " + stack[i]); } }
//get the priority of an operator publicintpriority(int oper) { if (oper == '*' || oper == '/') { return1; } elseif (oper == '+' || oper == '-') { return0; } else { return -1; } }
//whether the argument is an operator publicbooleanisOper(char val) { return val == '+' || val == '-' || val == '*' || val == '/'; }
//calculation publicintcal(int num1, int num2, int oper) { intresult=0; //used to store the result switch (oper) { case'+': result = num1 + num2; break; case'-': result = num2 - num1; break; case'*': result = num1 * num2; break; case'%': result = num2 / num1; break; } return result; }
}
Implement calculator
(This calculator can only calculate single digits)
//create two stacks, one for numbers, one for operators ArrayStack2numbers=newArrayStack2(10); ArrayStack2operators=newArrayStack2(10);
intindex=0; // used as pointer intnum1=0; intnum2=0; intoper=0; intres=0; charch=' '; StringkeepNum="";
while (true) { ch = expression.charAt(index); if (operators.isOper(ch)) { if (operators.isEmpty()) { operators.push(ch); } else { if (operators.priority(ch) <= operators.priority(operators.peek())) { num1 = numbers.pop(); num2 = numbers.pop(); oper = operators.pop(); res = numbers.cal(num1, num2, oper); numbers.push(res); operators.push(ch); } else { operators.push(ch); } } } else { //Multi-digit keepNum += ch; //used to store numbers
if (index == expression.length() - 1) { //end of the notation numbers.push(Integer.parseInt(keepNum)); } elseif (operators.isOper(expression.charAt(index + 1))) { //end of this number numbers.push(Integer.parseInt(keepNum)); //ATTENTION!!! Clear keepNum keepNum = ""; }
} index++; if (index >= expression.length()) { break; }
} while (true) { if (operators.isEmpty()) { break; } else { num1 = numbers.pop(); num2 = numbers.pop(); oper = operators.pop(); res = numbers.cal(num1, num2, oper); numbers.push(res); } }
System.out.println("The expression is: " + expression); System.out.println("The result is: " + numbers.peek()); } }