public class Calculator extends JFrame implements ActionListener{
private JTextField t;
private JPanel jp;
String op="";//操作
String input;
//boolean flag=true;
private String name[]={"C","Del"," ","/","7","8","9","*","4","5","6","-","1","2","3","+"," ","0",".","="};
private JButton b[]= new JButton[name.length];
public Calculator() {
this.setTitle("计算器");
t= new JTextField(20);
this.add(t,BorderLayout.NORTH);
jp= new JPanel(new GridLayout(5,4));
for(int i=0;i<b.length;i++) {
b[i]= new JButton(name[i]);
jp.add(b[i]);
b[i].addActionListener(this);
}
this.add(jp,BorderLayout.CENTER);
this.setSize(220,250);
this.setLocation(200, 200);//设置窗体出现的位置
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //设置窗体关闭的同时关闭
this.setVisible(true);
this.setResizable(false);
//validate();
}
public void actionPerformed(ActionEvent e)
{
int cnt=0;
String Command=e.getActionCommand();
if(Command.equals("+")||Command.equals("-")||Command.equals("*")||Command.equals("/")||Command.equals("."))
input+=" "+Command+" ";//设置输入
else if(Command.equals("C"))
input="";
else if(Command.equals("Del")) {
input= input.substring(0,input.length()-1);
}
else if(Command.equals("="))//等号时,则处理 input
{
input+= "="+count(input);
t.setText(input);
input="";
cnt=1;//判断是否结束一次运算
}
else if(Command.equals("."))
{
//contenTextField.append(".");
}
else
input+=Command;
if(cnt==0)
t.setText(input);
}
private String count(String input)
{
String str[];
str = input.split(" ");//
Stack<Double> s = new Stack<Double>();
double m = Double.parseDouble(str[0]);//
s.push(m);
for(int i=1;i<str.length;i++)
{
if(i%2==1)
{
if(str[i].compareTo("+")==0)
{
double help=Double.parseDouble(str[i+1]);
s.push(help);
}
if(str[i].compareTo("-")==0)
{
double help = Double.parseDouble(str[i+1]);
s.push(-help);
}
if(str[i].compareTo("*")==0)
{
double help = Double.parseDouble(str[i+1]);
double ans = s.peek();//取出栈顶元素
s.pop();//消栈
ans*=help;
s.push(ans);
}
if(str[i].compareTo("/")==0)
{
double help = Double.parseDouble(str[i+1]);
double ans = s.peek();
s.pop();
ans/=help;
s.push(ans);
}
}
}
double ans = 0d;//
while(!s.isEmpty())
{
ans+=s.peek();
s.pop();
}
String result = String.valueOf(ans);
return result;
}
}
int是整数型 换成浮点型
把int类型转成double类型计算就可以正常计算了 但是会出现精度丢失的问题 如果想要精确计算的话 可以用String类型 计算时转成double计算 然后通过
DecimalFormat dFormat = new DecimalFormat("######0.00");
dFormat.format(double1 * double2)
转回字符串就可以了