• 大小: 23KB
    文件类型: .java
    金币: 1
    下载: 0 次
    发布日期: 2021-06-05
  • 语言: Java
  • 标签:

资源简介

java使用后缀表达式实现计算器,其中有将一般数学运算式(7-9+5/5-5*6)转换成后缀表达式的方法,以及后缀表达式的求解方法

资源截图

代码片段和文件信息

package cn.asam.calculator;

import java.awt.EventQueue;

import javax.swing.Jframe;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.JSeparator;
import java.awt.Color;
import javax.swing.JButton;
import java.awt.Font;
import javax.swing.SwingConstants;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.math.BigDecimal;
import java.util.Stack;

public class Calculator {

private Jframe frmCalculator;
private JTextField inputTxt;
private JTextField result;
private JSeparator separator;
private JButton eight;
private JButton nine;
private JButton multiply;
private JButton four;
private JButton five;
private JButton six;
private JButton subtract;
private JButton one;
private JButton two;
private JButton three;
private JButton add;
private JButton dot;
private JButton zero;
private JButton divide;
private JButton btnEqual;
private JButton btnDel;

/**
 * Launch the application.
 */
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Calculator window = new Calculator();
window.frmCalculator.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

/**
 * Create the application.
 */
public Calculator() {
initialize();
}

/**
 * 获取传入参数按钮的文本
 * 
 * @param btn
 * @return
 */
private String getBtnText(JButton btn) {
String text = null;
text = btn.getText();
return text;
}

/**
 * 将按钮上的文本显示到输入运算式框中
 * 
 * @param str
 * @param inputTxt
 */
private void txtToInputTxt(String str JTextField inputTxt) {
String currentTxt = inputTxt.getText();
if (str.matches(“^[\\+\\-\\*\\/]$“) && currentTxt.matches(“^.+[\\+\\-\\*\\/]$“)) {
// 如果输入框中的最后一位是(+-*/)中的一位的,就将最后一位去掉,写上最新的符号
int strLength = currentTxt.length();
String rStr = currentTxt.substring(0 strLength - 1);
inputTxt.setText(rStr + str);
} else {
inputTxt.setText(currentTxt + str);
}
}

/**
 * 将传入的一般运算表达式计算出结果
 * 
 * @param inputTxt
 */
private void setResult(String inputTxt) {
String suffixExpre = toSuffix(inputTxt);
BigDecimal rSum = getSuffixResult(suffixExpre);
result.setText(rSum.doubleValue() + ““);
}

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
frmCalculator = new Jframe();
frmCalculator.setResizable(false);
frmCalculator.settitle(“Calculator“);
frmCalculator.getContentPane().setBackground(Color.DARK_GRAY);
frmCalculator.setBounds(800 200 386 454);
frmCalculator.setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE);

inputTxt = new JTextField();
inputTxt.setEditable(false);
inputTxt.setBackground(Color.WHITE);
inputTxt.setBorder(null);
inputTxt.setFont(new Font(“黑体“ Font.BOLD 32));
inputTxt.setHorizontalAlignment(SwingConstants.RIGHT);
inputTxt.setText(““);
inputTxt

评论

共有 条评论