带括号带键盘输入事件的计算器

这个博客介绍了一个使用Java实现的计算器程序,该计算器能够处理带括号的表达式,并支持键盘输入。它包括了按钮点击和键盘按键的事件监听,实现了基本的加、减、乘、除、括号等操作。用户可以输入数学表达式,程序会进行计算并显示结果。同时,博客中还包含了错误检查,确保输入的表达式符合规则。
摘要由CSDN通过智能技术生成


import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
public class Calculator extends JFrame{
 private Container container;
 private GridBagLayout layout; //定义布局方式为网格包布局
 private GridBagConstraints constraints;
 private JTextField displayfield;//计算结果显示区
 private String lastCommand;//保存+,-,*,/,=命令
 private double result;//保存计算结果
 private boolean start;
 private char[] c;
 public Calculator(){
  super("Calculator");
  container=getContentPane();
  layout=new GridBagLayout();
  container.setLayout(layout);
  constraints=new GridBagConstraints();
  start=true;
  result=0;
  constraints.fill=GridBagConstraints.BOTH;
  displayfield=new JTextField(20);
  displayfield.setHorizontalAlignment(JTextField.RIGHT);
  displayfield.setForeground(Color.BLUE);
  constraints.gridx=0;
  constraints.gridy=0;
  constraints.gridwidth=4;
  constraints.gridheight=2;
  constraints.fill=GridBagConstraints.BOTH;
  constraints.weightx=50;
  constraints.weighty=50;
  layout.setConstraints(displayfield,constraints);
  container.add(displayfield);
  
  ActionListener insert = new InsertAction(); //定义两个监视器
  ActionListener command = new CommandAction();
  KeyListener keyinsert =new InsertKey();
  addButton("Back",0,2,1,1,insert,keyinsert); //通过定义好的方法添加按钮
  addButton("CE",1,2,1,1,insert,keyinsert);
  addButton("CLEAR",2,2,2,1,insert,keyinsert);
  addButton("7",0,3,1,1,insert,keyinsert);
  addButton("8",1,3,1,1,insert,keyinsert);
  addButton("9",2,3,1,1,insert,keyinsert);
  addButton("+",3,3,1,1,insert,keyinsert);
  addButton("4",0,4,1,1,insert,keyinsert);
  addButton("5",1,4,1,1,insert,keyinsert);
  addButton("6",2,4,1,1,insert,keyinsert);
  addButton("-",3,4,1,1,insert,keyinsert);
  addButton("1",0,5,1,1,insert,keyinsert);
  addButton("2",1,5,1,1,insert,keyinsert);
  addButton("3",2,5,1,1,insert,keyinsert);
  addButton("*",3,5,1,1,insert,keyinsert);
  addButton("+/-",0,6,1,1,insert,keyinsert);
  addButton("0",1,6,1,1,insert,keyinsert);//只显示"-"号,"+"没有实用价值
  addButton(".",2,6,1,1,insert,keyinsert);
  addButton("/",3,6,1,1,insert,keyinsert);
  addButton("(",0,7,1,1,insert,keyinsert);
  addButton(")",1,7,1,1,insert,keyinsert);
  addButton("=",2,7,2,1,command,keyinsert);
  setSize(300,300); //设置窗口的大小
  setVisible(true); //设置窗口可见
 }
 private void addButton(String label,int row,int column,int with,int height,ActionListener listener ,KeyListener key ) {
  //定义添加按钮的方法
  JButton button=new JButton(label);
  constraints.gridx=row;
  constraints.gridy=column;
  constraints.gridwidth=with;
  constraints.gridheight=height;
  constraints.fill=GridBagConstraints.BOTH;
  button.addActionListener(listener);
  button.addKeyListener(key);
  layout.setConstraints(button,constraints);
  container.add(button);
  constraints.insets=new Insets(1,1,1,1);//设置按钮间的间距
  button.setForeground(Color.MAGENTA);
  button.setBorderPainted(true);
  button.setContentAreaFilled(true);
  button.setBounds(2,2,2,2);
  button.contains(5,5);
  //button.setEnabled(false);
  }
 private class InsertAction implements ActionListener {
  //定义Insert事件的方法
  public void actionPerformed(ActionEvent event) {

  String input=event.getActionCommand();
  if (start) {
  displayfield.setText(""); //默认计算区域为空
  start=false;
  }
  if(input.equals("+/-")) {
  displayfield.setText(displayfield.getText()+"-"); //如果开始输入的是"+/-",以负数显示
  }
  if(!input.equals("+/-")) {
   if(input.equals("Back")) { 
   if(displayfield.getText().length()>0) {
   displayfield.setText(displayfield.getText().substring(0, displayfield.getText().length()-1));
   }//如果单击退格,实现退格的功能
   }
   else if(input.equals("CE")||input.equals("CLEAR")) {

   displayfield.setText("");
   start=true;
   }
   else
     displayfield.setText(displayfield.getText()+input);
   }
   }
 }
 private class InsertKey implements KeyListener {
  //定义Insert事件的方法
  public void keyPressed(KeyEvent event) {
   if (start) {
    displayfield.setText(""); //默认计算区域为空
    start=false;
   }
    if(event.getKeyCode()==KeyEvent.VK_BACK_SPACE){
    if(displayfield.getText().l

为了应付作业而编的,一个新手,请大家多多指教。/** * Title: Calculator * Description: * Copyright: Copyright (c) 2004 * Company: CUIT * Calculator.java * Created on 2004年10月13日, 下午2:35 * @author jacktom * @version 1.0*/import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Calculator extends JFrame implements ActionListener{ Operator oper; String a,result; int type; boolean flag1=false; boolean flag2=false; boolean judge=true; int count=0; JTextField text; JPanel jpanel[]; JPanel jpanel1; JButton jbutton[]; String name[]={"0",".","-/+","+","=","1","2","3","-",")","4","5","6","*","(","7","8","9","/","CE"}; //Construct the JFrame public Calculator() { oper=new Operator(); setSize(250,300); setVisible(true); //Overridden so we can exit when window is closed this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { dispose(); System.exit(0); } }); Container con=getContentPane(); con.setLayout(new GridLayout(5,5)); text=new JTextField(12); text.setHorizontalAlignment(JTextField.RIGHT); jpanel1=new JPanel(); jpanel1.setLayout(new GridLayout(1,1)); jpanel1.add(text); jpanel=new JPanel[4]; for(int i=0;i<4;i++) { jpanel[i]=new JPanel(); jpanel[i].setLayout(new GridLayout(1,5)); } jbutton=new JButton[name.length]; //add button to panel for(int j=0;j=0;i--) { con.add(jpanel[i]); } } public void actionPerformed(ActionEvent e) { for(int i=0;i<10;i++) { if(e.getActionCommand().equals(String.valueOf(i))) if(flag1==false) { text.setText(String.valueOf(i)); flag1=true; } else { text.setText(text.getText()+i); } } if(e.getActionCommand().equals(".")) if(flag2==false&&count==0) { text.setText(text.getText()+"."); count++; flag1=true; } if(e.getActionCommand().equals("+")||e.getActionCommand().equals("-")||e.getActionCommand().equals("*")||e.getActionCommand().equals("/")) { if(judge) { a=text.getText(); oper.EvaluateExpression(a); } else judge=true; flag1=false; flag2=false; count=0; if(e.getActionCommand().equals("+")) { a="+"; oper.EvaluateExpression(a); } if(e.getActionCommand().equals("-")) { a="-"; oper.EvaluateExpression(a); } if(e.getActionCommand().equals("*")) { a="*"; oper.EvaluateExpression(a); } if(e.getActionCommand().equals("/")) { a="/"; oper.EvaluateExpression(a); } } if(e.getActionCommand().equals("=")) { if(judge) { a=text.getText(); oper.EvaluateExpression(a); } else judge=true; oper.EvaluateExpression("#"); text.setText(""); text.setText(String.valueOf(oper.CalculateResult())); flag1=false; flag2=false; count=0; } if(e.getSource()==jbutton[2]) { text.setText("-"+text.getText()); } if(e.getActionCommand().equals(")")) { a=text.getText(); oper.EvaluateExpression(a); oper.EvaluateExpression(")"); judge=false; } if(e.getActionCommand().equals("CE")) { text.setText(""); judge=true; count=0; flag1=false; flag2=false; oper=new Operator(); } if(e.getActionCommand().equals("(")) { oper.EvaluateExpression("("); } } /** * Main method * * @param args String[] */ public static void main(String args[]) { Calculator Cmain=new Calculator(); Cmain.pack(); }}/** * Operator.java * Description:用栈实现计算 * Created on 2004年10月13日, 下午3:35 * @author jacktom*/public class Operator{ StackY optr; //存放操作符 StackY opnd;//存放操作数 Puzhu p; boolean Mark; Operator() { p=new Puzhu(); optr=new StackY(); opnd=new StackY(); optr.push("#"); } public void EvaluateExpression(String s) { boolean mark=true; if(s=="+"||s=="-"||s=="*"||s=="/"||s=="("||s==")"||s=="#") { while(mark) { switch(p.Precede(optr.peek(),s)) { case -1: optr.push(s); mark=false; break; case 0: optr.pop(); mark=false; break; case 1: String theta=optr.pop(); String a =opnd.pop(); String b =opnd.pop(); if(a.indexOf(".",0)==-1&&b.indexOf(".",0)==-1) Mark=true; else Mark=false; double c=Double.valueOf(a).doubleValue(); double d=Double.valueOf(b).doubleValue(); double e=p.Operate(c,theta,d); String f=String.valueOf(e); if(theta=="/") Mark=false; if(Mark) opnd.push(f.substring(0,f.indexOf(".",0))); else opnd.push(f); break; } } } else opnd.push(s); } public String CalculateResult() { //double result=Double.valueOf(opnd.peek()).doubleValue(); return opnd.peek(); }}/** * Description:判断操作符的优先级并计算结果 * Created on 2004年10月13日, 下午4:00 * @author jacktom*/class Puzhu{ public Puzhu() {} public int Precede(String optr1,String optr2) { String[] A={"+","-","*","/","(",")","#"}; int[][] B={ {1,1,-1,-1,-1,1,1}, {1,1,-1,-1,-1,1,1}, {1,1,1,1,-1,1,1}, {1,1,1,1,-1,1,1}, {-1,-1,-1,-1,-1,0,2}, {1,1,1,1,2,1,1}, {-1,-1,-1,-1,-1,2,0}, }; int i=0,j=0,k; while(i<7) { if(A[i]==optr1) { break; } i++; } while(j<7) { if(A[j]==optr2) { break; } j++; } k=B[i][j]; return k; } public double Operate(double a,String oper,double b) { double c=0; if(oper=="+") c=a+b; if(oper=="-") c=b-a; if(oper=="*") c=a*b; if(oper=="/") c=b/a; return c; }}/** * StackY.java * Description:堆栈的基本操作实现 * Created on 2004年10月13日, 下午3:05 * @author jacktom*/public class StackY { private int maxSize; // size of stack array private String[] stackArray; private int top; // top of stack public StackY(int s) // constructor { maxSize = s; // set array size stackArray = new String[maxSize]; // create array top = -1; // no items yet }public StackY() // constructor { maxSize = 20; // set array size stackArray = new String[maxSize]; // create array top = -1; // no items yet } public void push(String j) // put item on top of stack { top++; stackArray[top] = j; // increment top, insert item } public String pop() // take item from top of stack { return stackArray[top--]; // access item, decrement top } public String peek() // peek at top of stack { return stackArray[top]; } public boolean isEmpty() // true if stack is empty { return (top == 0); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值