计算器
Java
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Stack;
import javax.swing.*;
class MyException extends Exception{
public MyException() {
super();
}
public MyException(String message) {
super(message);
}
}
class SwingConsole{
public static void run(final JFrame f,final int width,final int height){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
f.setTitle(f.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(width,height);
f.setVisible(true);
}
});
}
}
public class MyCalculator extends JFrame{
private JTextField textField;
private String input;
private String operator;
public MyCalculator() {
input = "";
operator = "";
Container container = this.getContentPane();
JPanel panel = new JPanel();
textField = new JTextField(30);
textField.setEditable(false);
textField.setHorizontalAlignment(JTextField.LEFT);
textField.setPreferredSize(new Dimension(200,30));
container.add(textField, BorderLayout.NORTH);
String[] name= {"7","8","9","+","4","5","6","-","1","2","3","*","0","C","=","/"};
panel.setLayout(new GridLayout(4,4,1,1));
for(int i=0;i<name.length;i++) {
JButton button = new JButton(name[i]);
button.addActionListener(new MyActionListener());
panel.add(button);
}
container.add(panel,BorderLayout.CENTER);
}
class MyActionListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
int cnt=0;
String actionCommand = e.getActionCommand();
if(actionCommand.equals("+") || actionCommand.equals("-") || actionCommand.equals("*")
|| actionCommand.equals("/")) {
input += " " + actionCommand + " ";
}
else if(actionCommand.equals("C")) {
input = "";
}
else if(actionCommand.equals("=")) {
try {
input+= "="+calculate(input);
} catch (MyException e1) {
if(e1.getMessage().equals("Infinity"))
input+= "=" + e1.getMessage();
else
input = e1.getMessage();
}
textField.setText(input);
input="";
cnt = 1;
}
else
input += actionCommand;
if(cnt == 0)
textField.setText(input);
}
}
private String calculate(String input) throws MyException{
String[] comput = input.split(" ");
Stack<Double> stack = new Stack<>();
Double m = Double.parseDouble(comput[0]);
stack.push(m);
for(int i = 1; i < comput.length; i++) {
if(i%2==1) {
if(comput[i].equals("+"))
stack.push(Double.parseDouble(comput[i+1]));
if(comput[i].equals("-"))
stack.push(-Double.parseDouble(comput[i+1]));
if(comput[i].equals("*")) {
Double d = stack.peek();
stack.pop();
stack.push(d*Double.parseDouble(comput[i+1]));
}
if(comput[i].equals("/")) {
double help = Double.parseDouble(comput[i+1]);
if(help == 0)
throw new MyException("Infinity");
double d = stack.peek();
stack.pop();
stack.push(d/help);
}
}
}
double d = 0d;
while(!stack.isEmpty()) {
d += stack.peek();
stack.pop();
}
String result = String.valueOf(d);
return result;
}
public static void main(String[] args) {
SwingConsole.run(new MyCalculator(), 250, 300);
}
}
Py
import re
import tkinter
import tkinter.messagebox
def buttonClik(btn):
content = contentVar.get()
if content.startswith('.'):
content = '0' + content
if btn in '0123456789':
content += btn
elif btn == '.':
lastPart = re.split(r'\+|-|\*|/', content)[-1]
if '.'in lastPart:
tkinter.messagebox.showerror('错误', '重复出现的小数点')
return
else:
content += btn
elif btn == 'C':
content = ''
elif btn == '=':
try:
content = str(eval(content))
except:
tkinter.messagebox.showerror('错误', '表达式有误')
return
elif btn in operators:
if content.endswith(operators):
tkinter.messagebox.showerror('错误', '不允许存在连续运算符')
return
content += btn
elif btn == 'Sqrt':
n = content.split('.')
if all(map(lambda x: x.isdigit(), n)):
content = eval(content)**0.5
else:
tkinter.messagebox.showerror('错误', '表达式错误')
return
contentVar.set(content)
root = tkinter.Tk()
root.geometry('300x270+400+100')
root.resizable(False, False)
root.title('计算器')
contentVar = tkinter.StringVar(root, '')
contentEntry = tkinter.Entry(root, textvariable=contentVar)
contentEntry['state'] = 'readonly'
contentEntry.place(x=10, y=10, width=280, height=20)
btnClear = tkinter.Button(root, text='C', bg='red',
command=lambda: buttonClik('C'))
btnClear.place(x=40, y=40, width=80, height=20)
btnCompute = tkinter.Button(
root, text='=', bg='yellow', command=lambda: buttonClik('='))
btnCompute.place(x=170, y=40, width=80, height=20)
digits = list('0123456789.') + ['Sqrt']
index = 0
for row in range(4):
for col in range(3):
d = digits[index]
index += 1
btnDigit = tkinter.Button(
root, text=d, command=lambda x=d: buttonClik(x))
btnDigit.place(x=20 + col * 70, y=80 + row * 50, width=50,
height=20)
operators = ('+', '-', '*', '/', '**', '//')
for index, operator in enumerate(operators):
btnOperator = tkinter.Button(
root, text=operator, bg='orange', command=lambda x=operator: buttonClik(x))
btnOperator.place(x=230, y=80 + index * 30, width=50, height=20)
root.mainloop()