写了一个个位数的四则运算跟大家交流,如果大家对多位数的四则运算感兴趣可以交流学习
class="java" name="code">
import java.util.LinkedList;
class Stack<T>{
private LinkedList<T> memory = new LinkedList<T>();
public void push(T arg){
memory.addFirst(arg);
}
public T peek(){
return memory.peek();
}
public T pop(){
return memory.poll();
}
public boolean empty(){
return memory.isEmpty();
}
}
public class Arithmometer {
private char[] express;
private int result;
private Stack<Integer> data = new Stack<Integer>();
private Stack<Character> oprator = new Stack<Character>();
private void init(String express){
this.express = express.toCharArray();
}
private void pushData(char operNumber){
data.push(operNumber - '0');
}
private void pushOperator(char operator){
oprator.push(operator);
}
private boolean needCalculate(char operator){
if(oprator.empty()){
return false;
}
switch(operator){
case '(':
return false;
case ')':
if(oprator.peek() == '('){
oprator.pop();
return false;
}
return true;
case '+':
case '-':
if(oprator.peek() == '+' || oprator.peek() == '-'){
return true;
}
if(oprator.peek() == '*' || oprator.peek() =='/'){
return true;
}
break;
case '*':
case '/':
if(oprator.peek() == '*' || oprator.peek() =='/'){
return true;
}
return false;
default: return false;
}
return false;
}
private void doOneStepCalcute(){
int second = data.pop();
int first = data.pop();
int operator = oprator.pop();
int result = 0;
switch(operator){
case '+':
result = first + second;
break;
case '-':
result = first - second;
break;
case '*':
result = first * second;
break;
case '/':
result = first/second;
break;
}
data.push(result);
}
private int calculating(){
for(int i = 0; i < express.length; i++){
if(express[i] >= '0' && express[i] <='9'){
pushData(express[i]);
}
else{
while(needCalculate(express[i])){
doOneStepCalcute();
}
if(express[i] != ')'){
pushOperator(express[i]);
}
}
}
while(!oprator.empty()){
doOneStepCalcute();
}
return data.peek();
}
public int calculate(String express){
init(express);
return calculating();
}
public static void main(String[] args){
Arithmometer arithmometer = new Arithmometer();
int result = arithmometer.calculate("1+2*3");
System.out.println(result);
}
}