表达式求值 [第一次用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));	
				}//if
				else	s.push(str.charAt(i));
			}//else
		}//for
		while(!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;
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值