计算器(java)

记得输入时用弹窗的按钮或者键盘(切换成英文)

 

我用了两个类来实现这些功能

Face类用来实现界面;

ButtonEvent是接口ActionListener的实现类,用来响应事件;

ButtonEvent类包含actionPerformed(ActionEvent e)、int sign(StringBuffer str1,String str,int i)、String[] division(String str)、 double operation(String [] str)、int prior(String str)这些方法;

首先我们通过后缀表达式来计算,要得到后缀表达式,必须把操作数与运算符分开。

用String[] division(String str)方法来分开操作数与运算符,返回为字符串数组;

actionPerformed(ActionEvent e)用来将表达式转换成后缀表达式;

int prior(String str)计算运算符之间的优先级;

double operation(String [] str)计算结果;

package Calculator1;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Stack;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;

class Face {
	JPanel panel1=new JPanel();
	JPanel panel2=new JPanel();
	JTextArea textarea=new JTextArea();
	String str1[]= {"1","2","3",
			        "4","5","6",
			         "7","8","9",
	                "0",".","*","/",
	                "+","-","=","(",")"};
	JButton button[]=new JButton[str1.length];
	Face(String title) {
		JFrame frame=new JFrame(title);
		panel1.add(textarea);
		for(int i=0;i<str1.length;i++) {
		  button[i]=new JButton(str1[i]);
		  panel2.add(button[i]);
		}
		frame.add(BorderLayout.NORTH,textarea);
		frame.add(BorderLayout.CENTER,panel2);
	    frame.setSize(250, 200);
		frame.setVisible(true);
		frame.setLocation(800,400);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		button[0].addActionListener(new ButtonEvent(this));
		button[1].addActionListener(new ButtonEvent(this));
		button[2].addActionListener(new ButtonEvent(this));
		button[3].addActionListener(new ButtonEvent(this));
		button[4].addActionListener(new ButtonEvent(this));
		button[5].addActionListener(new ButtonEvent(this));
		button[6].addActionListener(new ButtonEvent(this));
		button[7].addActionListener(new ButtonEvent(this));
		button[8].addActionListener(new ButtonEvent(this));
		button[9].addActionListener(new ButtonEvent(this));
		button[10].addActionListener(new ButtonEvent(this));
		button[11].addActionListener(new ButtonEvent(this));
		button[12].addActionListener(new ButtonEvent(this));
		button[13].addActionListener(new ButtonEvent(this));
		button[14].addActionListener(new ButtonEvent(this));
		button[15].addActionListener(new ButtonEvent(this));
		button[16].addActionListener(new ButtonEvent(this));
		button[17].addActionListener(new ButtonEvent(this));
		
	}
}
class ButtonEvent implements ActionListener{
	Face face;
	public ButtonEvent(Face face) {
		this.face=face;
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		int k=0;//计算括号数目
		String str=face.textarea.getText();//获得文本框上的内容
		Stack<String> stack=new Stack<String>(); //定义一个栈
		if(e.getActionCommand().equals("=")) {
			String str2[]=division(str);     //将操作数与运算符分开,返回一个字符串数组
			for(int i=0;i<str.length();i++)  //得到运算符(的个数,因为后缀表达式不含有();
				if(str.charAt(i)=='(')
					k++;
			String getPostfit[]=new String[str2.length-2*k];//定义一个字符串数组,用来存储后缀表达式;
			int n=0;
			for(int i=0;i<str2.length;i++) {   //将表达式转换成后缀表达式str2[]是存储分割操作数与运算符后的数组
				//if(str2[i].equals("(")||str2[i].equals(")")||str2[i].equals("*")||str2[i].equals("/")||str2[i].equals("+")||str2[i].equals("-")) {
			  if(str2[i].equals("(")) {         
				  stack.push(str2[i]);
			  }else if(str2[i].equals(")")) {
				  while(!stack.isEmpty()&&!stack.peek().equals("(")) {
					  getPostfit[n++]=stack.pop();
				  }
				  stack.pop();
			  }else if(str2[i].equals("*")||str2[i].equals("/")||str2[i].equals("+")||str2[i].equals("-")) {
				  if(!stack.isEmpty()) {
				  while(!stack.peek().equals("(")&&prior(stack.peek())<=prior(str2[i])) {
					  getPostfit[n++]=stack.pop();
					  if(stack.isEmpty())
						  break;
				  }
				  }
				  stack.push(str2[i]);
			  }else {
				  getPostfit[n++]=str2[i];
			  }
			}
			 while(!stack.isEmpty()) {
				  getPostfit[n++]=stack.pop();
			  }
			System.out.print("后缀式表达式为");
		    for(int i=0;i<getPostfit.length;i++)
		    	System.out.print(getPostfit[i]+" ");
		    System.out.println();
		    System.out.println("=============");
		    operation(getPostfit);//计算得出结果
			}else {
				face.textarea.append(e.getActionCommand());
			}
				
	}
	public String[] division(String str) {  
		StringBuffer str1=new StringBuffer(str);
		str1.append("                            ");
		int k=0;
		for(int i=0;i<str.length();i++) {
			char c=str.charAt(i);
			if(c=='+'||c=='-'||c=='*'||c=='/'||c==')'||c=='(') {
				if(i!=str1.length()-1&&i!=0) {
					if(str1.charAt(i+1)!='+'||str1.charAt(i+1)!='-'||str1.charAt(i+1)!='*'||str1.charAt(i+1)!='/') {
						k=sign(str1,str,i);
						if(str1.charAt(k-1)!=' ') {
							str1.insert(k," ");
						}
						k=sign(str1,str,i);
						if(str1.charAt(k+1)!=' ') {
							str1.insert(k+1," ");
						}
					}
				}else if(i==0){
					str1.insert(1," ");
				}else {
					k=sign(str1,str,i);
					str1.insert(k," ");
				}
			}
		}
		str=str1.toString();
		String []str2=str.split(" ");
		return str2;
	}
	public int sign(StringBuffer str1,String str,int i) {
		int k=0,n=-1;
              for(k=0;k<str1.length();k++) {
            	  if(str1.charAt(k)!=' ')
            		  n++;
				if(n==i&&str1.charAt(k)==str.charAt(i))
					break ;
				}
              return k;
	}
public double operation(String [] str) {
	double result=0.0;
	double d1;
	double d2;
	Stack<Double> sta=new Stack<Double>();
	for(int i=0;i<str.length;i++) {
		if(str[i].equals("*")) {
			result=sta.pop()*sta.pop();
			sta.push(result);
		}else if(str[i].equals("/")) {
			d1=sta.pop();
			d2=sta.pop();
			result=d2/d1;
			sta.push(result);
		}else if(str[i].equals("+")) {
			result=sta.pop()+sta.pop();
			sta.push(result);
		}else if(str[i].equals("-")) {
			d1=sta.pop();
			d2=sta.pop();
			result=d2-d1;
			sta.push(result);
	    }else if(str[i].isEmpty()){
	    	
	    }else {
	    	sta.push(Double.valueOf(str[i]));
	    }
	}
	System.out.println("计算结果为"+result);
	face.textarea.append("="+result);
	return result;
}
public int prior(String str) {
	if("(".equals(str))
		return 3;
	else if("*".equals(str)||"/".equals(str))
		return 2;
	else if("+".equals(str)||"-".equals(str))
		return 1;
	return 0;
}
}
public class Surface {

	public static void main(String[] args) {
		new Face("计算器");
		

	}
}


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值