计算器的设计与实现
接下来就进入第一个实验啦,编写一个简单的计算器
实验准备
在这里记录一下老师讲的算法,用栈来实现这个实验,主要思想就是把中缀表示式转换成后缀表达式,方便计算机的阅读与计算。
代码
算法的实现
判断是否为括号,且遇到左括号时直接压栈,遇到右括号时把左括号前的运算符弹出,直到遇到左括号:
```java
private static boolean checkString(String str) {
// 判断括号
Stack<Character> sta = new Stack<Character>();
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == '(') {
sta.push(str.charAt(i));
} else if (str.charAt(i) == ')') {
if (sta.empty() || sta.peek() != '(') {
return false;
} else {
sta.pop();
}
}
}
###### 定义运算符方法:
```java
Stack<Double> stack = new Stack<Double>();
StringTokenizer token = new StringTokenizer(s, "$", false);
while (token.hasMoreTokens()) {
String t = token.nextToken();
if((t.equals("+")||t.equals("-")||t.equals("*")||t.equals("/"))&&stack.size()<2) {
return "Bad str";
}
if (t.equals("+")) {
stack.push(stack.pop() + stack.pop());
} else if (t.equals("-")) {
double a = stack.pop();
stack.push(stack.pop() - a);
} else if (t.equals("*")) {
stack.push(stack.pop() * stack.pop());
} else if (t.equals("/")) {
double a = stack.pop();
stack.push(stack.pop() / a);
} else {
stack.push(Double.parseDouble(t));
}
}
进行运算:
```java
private static String getcalc(String str) {
if (str.isEmpty()) {
return str;
}
Stack<Character> sta = new Stack<Character>();
String s = "$";
int i = 0;
if (str.charAt(0) == '(') {
sta.push('(');
i++;
}
boolean flag = false;
for (; i < str.length(); i++) {
if (str.charAt(i) == '+' && (i == 0 || (str.charAt(i - 1) < '0' && str.charAt(i - 1) != ')')))
i++;
if (str.charAt(i) == '-') {
flag = true;
i++;
}
while (i < (int) str.length() && ((str.charAt(i) >= '0' && str.charAt(i) <= '9') || str.charAt(i) == '.' || str.charAt(i)=='E')) {
if (flag) {
s += "-$";
flag = false;
}
s += str.charAt(i);
i++;
}
s += "$";
if (i < (int) str.length()) {
if (sta.empty() || str.charAt(i) == '(')
sta.push(str.charAt(i));
else if (str.charAt(i) == '+' || str.charAt(i) == '-') {
while (sta.size() > 0 && sta.peek() != '(') {
s += sta.pop() + "$";
}
sta.push(str.charAt(i));
} else if (str.charAt(i) == '*' || str.charAt(i) == '/') {
while (sta.size() > 0 && (sta.peek() == '*' || sta.peek() == '/')) {
s += sta.pop() + "$";
}
sta.push(str.charAt(i));
} else {
while (sta.size() > 0 && sta.peek() != '(') {
s += sta.pop() + "$";
}
sta.pop();
}
}
}
while (sta.size() > 0) {
s += sta.pop() + "$";
}
###### 类及calc方法:
```java
public class calculator {
public static String calc(String str) {
if (checkString(str) == false) { //检查括号匹配
return "Bad str";
}
str = getcalc(str); //进行计算(此时仅包含基本运算符和小括号)
if(str.equals("Bad str")) {
return str;
}
图形界面的设计
以及把calculator类的calc方法封装到这个类来
import javax.script.*;
import java.util.Stack;
import java.util.StringTokenizer;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.text.Caret;
public class demo3 {
JFrame frame;
private JTextField jtf1;
private JTextField jtf2;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
demo3 window = new demo3();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public demo3() {
design();
}
private void design() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 520);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton jb1 = new JButton("1");
jb1.setBackground(Color.LIGHT_GRAY);
jb1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String text=jtf1.getText();
jtf1.setText(text+"1");
}
});
jb1.setBounds(30,200,66,40);
frame.getContentPane().add(jb1);
JButton jb2 = new JButton("2");
jb2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String text=jtf1.getText();
jtf1.setText(text+"2");
}
});
jb2.setBackground(Color.LIGHT_GRAY);
jb2.setBounds(111,200,66,40);
frame.getContentPane().add(jb2);
JButton jb3 = new JButton("3");
jb3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String text=jtf1.getText();
jtf1.setText(text+"3");
}
});
jb3.setBackground(Color.LIGHT_GRAY);
jb3.setBounds(192,200,66,40);
frame.getContentPane().add(jb3);
JButton jb4 = new JButton("4");
jb4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String text=jtf1.getText();
jtf1.setText(text+"4");
}
});
jb4.setBackground(Color.LIGHT_GRAY);
jb4.setBounds(30,260,66,40);
frame.getContentPane().add(jb4);
JButton jb5 =new JButton("5");
jb5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String text=jtf1.getText();
jtf1.setText(text+"5");
}
});
jb5.setBackground(Color.LIGHT_GRAY);
jb5.setBounds(111, 260, 66, 40);
frame.getContentPane().add(jb5);
JButton jb6 = new JButton("6");
jb6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String text=jtf1.getText();
jtf1.setText(text+"6");
}
});
jb6.setBackground(Color.LIGHT_GRAY);
jb6.setBounds(192,260,66,40);
frame.getContentPane().add(jb6);
JButton jb7 = new JButton("7");
jb7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String text=jtf1.getText();
jtf1.setText(text+"7");
}
});
jb7.setBackground(Color.LIGHT_GRAY);
jb7.setBounds(30,320,66,40);
frame.getContentPane().add(jb7);
JButton jb8 = new JButton("8");
jb8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String text=jtf1.getText();
jtf1.setText(text+"8");
}
});
jb8.setBackground(Color.LIGHT_GRAY);
jb8.setBounds(111,320,66,40);
frame.getContentPane().add(jb8);
JButton jb9 = new JButton("9");
jb9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String text=jtf1.getText();
jtf1.setText(text+"9");
}
});
jb9.setBackground(Color.LIGHT_GRAY);
jb9.setBounds(192,320,66,40);
frame.getContentPane().add(jb9);
JButton jb10 = new JButton(".");
jb10.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String text=jtf1.getText();
jtf1.setText(text+".");
}
});
jb10.setBackground(Color.LIGHT_GRAY);
jb10.setBounds(192,380,66,40);
frame.getContentPane().add(jb10);
JButton jb0 = new JButton("0");
jb0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String text=jtf1.getText();
jtf1.setText(text+"0");
}
});
jb0.setBackground(Color.LIGHT_GRAY);
jb0.setBounds(30,380,147,40);
frame.getContentPane().add(jb0);
JButton j1b1 = new JButton("C");
j1b1.setBackground(Color.LIGHT_GRAY);
j1b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String text=jtf1.getText();
int t=text.length()-1;
if(t<0) {
JOptionPane.showMessageDialog(null, "已经没有了((");
}
else {
text=text.substring(0, t);
jtf1.setText(text);
}
}
});
j1b1.setBounds(273,200,60,40);
frame.getContentPane().add(j1b1);
JButton j1b2 = new JButton("X");
j1b2.setBackground(Color.LIGHT_GRAY);
j1b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
jtf1.setText("");
jtf2.setText("");
}
});
j1b2.setBounds(354,200,66,40);
frame.getContentPane().add(j1b2);
JButton j1b3 = new JButton("+");
j1b3.setBackground(Color.LIGHT_GRAY);
j1b3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String text=jtf1.getText();
jtf1.setText(text+"+");
}
});
j1b3.setBounds(273,260,66,40);
frame.getContentPane().add(j1b3);
JButton j1b4 = new JButton("-");
j1b4.setBackground(Color.LIGHT_GRAY);
j1b4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String text=jtf1.getText();
jtf1.setText(text+"-");
}
});
j1b4.setBounds(354,260,66,40);
frame.getContentPane().add(j1b4);
JButton j1b5 = new JButton("/");
j1b5.setBackground(Color.LIGHT_GRAY);
j1b5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String text=jtf1.getText();
jtf1.setText(text+"/");
}
});
j1b5.setBounds(354,320,66,40);
frame.getContentPane().add(j1b5);
JButton j1b6 = new JButton("*");
j1b6.setBackground(Color.LIGHT_GRAY);
j1b6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String text=jtf1.getText();
jtf1.setText(text+"*");
}
});
j1b6.setBounds(273,320,66,40);
frame.getContentPane().add(j1b6);
JButton j1b7 = new JButton("(");
j1b7.setBackground(Color.LIGHT_GRAY);
j1b7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String text=jtf1.getText();
jtf1.setText(text+"(");
}
});
j1b7.setBounds(273,380,66,40);
frame.getContentPane().add(j1b7);
JButton j1b8 = new JButton(")");
j1b8.setBackground(Color.LIGHT_GRAY);
j1b8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String text=jtf1.getText();
jtf1.setText(text+")");
}
});
j1b8.setBounds(354,380,66,40);
frame.getContentPane().add(j1b8);
JButton j2b1 = new JButton("=");
j2b1.setBackground(Color.orange);
j2b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String text=jtf1.getText();
jtf2.setText(calculator.calc(text));
}
});
j2b1.setBounds(30,140,66,40);
frame.getContentPane().add(j2b1);
jtf1 = new JTextField();
jtf1.setBounds(30,30,390,50);
frame.getContentPane().add(jtf1);
jtf1.setColumns(10);
jtf2 = new JTextField();
jtf2.setBackground(Color.WHITE);
jtf2.setBounds(111,140,309,40);
frame.getContentPane().add(jtf2);
jtf2.setColumns(10);
}
}
最后结果就是这样的啦,还是可以进行一些带括号的四则运算的