本文主要是介绍表达式求值 [第一次用Java写,纪念一下 ],希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在章鱼哥的帮助下,终于完成了~
这个只能用来进行个位数的运算,只有+、-、*、/和括号。。呃呃,
不过稍微改进一下就可以多位数了。。
面壁思过ing...
package com.zjk.calculator;import java.util.Stack;import javax.swing.JOptionPane;public class calculator {private static final Object String = null;public static void main(String[] args){Stack<Integer> num = new Stack<Integer>();calculator c = new calculator();String str = JOptionPane.showInputDialog(null,String);String s = c.changeCalc(str); //转换后的后缀表达式// System.out.println(s);for(int i = 0; i < s.length(); i++){if(c.isOperater(s.charAt(i)) && !num.empty()){int tmp = 0;int c1 = num.pop();int c2 = num.pop();if(s.charAt(i) == '+') tmp = c1 + c2;else if(s.charAt(i) == '-') tmp = c2 - c1;else if(s.charAt(i) == '*') tmp = c1 * c2;else if(s.charAt(i) == '/') tmp = c2 / c1;num.push(tmp);// System.out.println("c1: "+c1+" c2: "+c2+" tmp:"+tmp);}else num.push(s.charAt(i) - '0');}JOptionPane.showMessageDialog(null,num.pop());//System.out.println(num.pop());}//求后缀表达式public String changeCalc(String str){ String ans = "";Stack<Character> s = new Stack<Character>();for(int i = 0; i<str.length(); i++){// System.out.println("i = "+i+" ch="+str.charAt(i));if(!isOperater(str.charAt(i))) ans += str.charAt(i);else {if(str.charAt(i) == '(') s.push(str.charAt(i));else if(str.charAt(i) == ')'){while(!s.empty() && s.peek()!='(') ans += s.pop();s.pop();}else if(!s.empty()){char temp = s.peek();if(cmp(str.charAt(i),temp) <= 0) {while(!s.empty() && cmp(str.charAt(i),s.peek()) <= 0) ans += s.pop();s.push(str.charAt(i));}else s.push(str.charAt(i)); }//ifelse s.push(str.charAt(i));}//else}//forwhile(!s.empty()) ans += s.pop();return ans;}//比较优先级public int cmp(char a,char b){int p1=0,p2=0;if('+' == a || '-' == a) p1 = 1;if('*' == a || '/' == a) p1 = 2;if('+' == b || '-' == b) p2 = 1;if('*' == b || '/' == b) p2 = 2;return p1-p2;}//判断是否为操作符public boolean isOperater(char ch){if(ch != '+' && ch != '-' && ch !='*' && ch != '/' && ch != '(' && ch != ')')return false; return true;}
}
这篇关于表达式求值 [第一次用Java写,纪念一下 ]的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!