首页 > 编程 > Java > 正文

整数四则运算的java实现-栈和队列的使用练习

2019-11-08 18:35:08
字体:
来源:转载
供稿:网友

数据结构大作业做简易解释器,要使用四则运算,先写到main里面试验一下,在做成单独的函数以备调用

import java.util.LinkedList;

import java.util.Queue;import java.util.Stack;public class calTest {/*** @param args*/public static void main(String[] args) {// TODO Auto-generated method stubString s="2*7-9+6/8*9-93*5=";Stack<String> num=new Stack<String>();//放变量的栈Stack<Character> sym =new Stack<Character>();//放运算符的栈//nums数组存放所有需要计算的数字或变量String[] nums = s.split("[+*-/=]");//把要计算的数字存放到队列中Queue<String> queue = new LinkedList<String>();for(int i=0;i<nums.length;i++){queue.offer(nums[i]);}//syms存放所有运算符String syms="";for(int i=0;i<s.length();i++){  if(s.charAt(i)=='+'|s.charAt(i)=='-'|s.charAt(i)=='*'|s.charAt(i)=='/'|s.charAt(i)=='='){  syms+=s.charAt(i);  }}//把与运算符存放到队列里Queue<Character> queue2 = new LinkedList<Character>();for(int i=0;i<syms.length();i++){queue2.offer(syms.charAt(i));}//开始计算//当符号队列不空的时候while(!queue2.isEmpty()){int num1=0;int num2=0;if(sym.isEmpty()){if(num.isEmpty()){num.push(queue.poll());}sym.push(queue2.poll());num.push(queue.poll());}else{char SymPeek=sym.peek();char Q2Peek=queue2.peek();switch(SymPeek){case('+'):{if(Q2Peek=='+'|Q2Peek=='-'|Q2Peek=='='){sym.pop();int result=0;num1=Integer.parseInt(num.pop());num2=Integer.parseInt(num.pop());result=num1+num2;num.push(result+"");}else{num.push(queue.poll());sym.push(queue2.poll());}break;}case('-'):{if(Q2Peek=='+'|Q2Peek=='-'|Q2Peek=='='){sym.pop();int result=0;num1=Integer.parseInt(num.pop());num2=Integer.parseInt(num.pop());result=num2-num1;num.push(result+"");}else{num.push(queue.poll());sym.push(queue2.poll());}break;}case('*'):{sym.pop();int result=0;num1=Integer.parseInt(num.pop());num2=Integer.parseInt(num.pop());result=num1*num2;num.push(result+"");break;}case('/'):{sym.pop();int result=0;num1=Integer.parseInt(num.pop());num2=Integer.parseInt(num.pop());result=num2/num1;num.push(result+"");break;}}}} while(!num.isEmpty()){System.out.PRintln("结果是:"+num.pop());} }}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表