用Java写的计算器
package com.wenbo.myprogrem.day15;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Caculator implements ActionListener{
String result="0";
String oper="+";//运算符
Double res;
StringBuilder sb=new StringBuilder();
JTextField jtf = new JTextField(10);
private boolean append=false;
public Caculator(){
JFrame jf = new JFrame("简易计算器");
JPanel jp = new JPanel();
jp.setLayout(new GridLayout(5,4));
String[] lab = {"Backs","CE","E","+","7","8","9",
"-","4","5","6","*","1","2","3",
"/","0","+/-",".","="};
for (int i=0; i <20; i++) {
JButton jb = new JButton(lab[i]);
jb.addActionListener(this);//给每个按钮注册监听器
jp.add(jb);
}
jf.setResizable(false);
jf.add(jp);
jtf.addActionListener(this);
jf.add(jtf,BorderLayout.NORTH);
jf.setSize(320,240);//像素
jf.setLocation(300,200);//设置出现位置
jf.setVisible(true);
jf.setDefaultCloseOperation(//设置X
JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
String comm=e.getActionCommand();//获得按钮上的文字
System.out.println(comm);
if("0123456789".indexOf(comm)!=-1){
if(append){//追加,刚开始是false按完数字键之后是变成true
String temp=jtf.getText();
jtf.setText(temp+comm);
}else{//替换
jtf.setText(comm);
append=true;
}
}else if("+-/*".indexOf(comm)!=-1){//当按到运算符时的处理
result=jtf.getText();//把输入框的内容存起来
oper=comm;
append=false;//不显示运算符,等待下次输入数字
}else if("=".equals(comm)){//计算过程
String s2=jtf.getText();
double d1=Double.parseDouble(result);
double d2=Double.parseDouble(s2);
if("+".equals(oper)){
d1=d1+d2;
}else if("*".equals(oper)){
d1=d1*d2;
}else if("/".equals(oper)){
d1=d1/d2;
}
result=d1+"";//将计算后的结果显示在输入框中
jtf.setText(result);
append=false;
}else if(".".equals(comm)){
String temp=jtf.getText();
if(temp.indexOf(".")==-1){
jtf.setText(temp+".");
append=true;
}
}else if("+/-".equals(comm)){
String temp=jtf.getText();
if(temp.startsWith("-")){//如果是以-开头的数
jtf.setText(temp.substring(1));//用substring截取从第二个字符开始,前面的-不要
}else{
jtf.setText("-"+temp);
}
append=true;
}else if("CE".equals(comm)||"C".equals(comm)){
jtf.setText("0");
}else if("Backs".equals(comm)){
}
}
public static void main(String[] args) {
new Caculator();
}
}