个位数四则运算_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > 个位数四则运算

个位数四则运算

 2013/12/4 18:26:05  Vitas_Wang  程序员俱乐部  我要评论(0)
  • 摘要:写了一个个位数的四则运算跟大家交流,如果大家对多位数的四则运算感兴趣可以交流学习importjava.util.LinkedList;classStack<T>{privateLinkedList<T>memory=newLinkedList<T>();publicvoidpush(Targ){memory.addFirst(arg);}publicTpeek(){returnmemory.peek();}publicTpop(){returnmemory
  • 标签:
写了一个个位数的四则运算跟大家交流,如果大家对多位数的四则运算感兴趣可以交流学习
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);
   }
}
  • 相关文章
发表评论
用户名: 匿名