没有任何校验,而且不按照优先级进行运算的计算器...
突然想起几年前用JAVA费劲写了个计算器的布局,今天突然发现当初耗时很久的界面这么容易实现...
四则运算的算法曾经在学数据结构的时候写过....不过在我写的这个代码中,由于为了简单,省略的很多内容,因而不容易实现...
不过如果只是两个数字的运算,在正确的输入下,还是可以返回正确结果的...
import java.awt.*;
import java.awt.event.*;
public class TestJSQ {
public static void main(String[] args) {
GridLayout grid = new GridLayout(4,4,5,5);
Frame f = new Frame("简单计算器");
Panel p = new Panel();
p.setLayout(grid);
final TextField tf = new TextField(40);
tf.setSize(100, 100);
f.add(tf,"North");
ActionListener action = new ActionListener(){
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand());
String str = e.getActionCommand();
if(str.equals("=")){
char[] ch = tf.getText().toCharArray();
Double[] dl = new Double[20];
char[] ys = new char[19];
boolean cx = false;//出现小数点后变为true
int count = 1;
int j=0;
int zf = 1;
for(int i=0;i<ch.length;i++){
if(ch[0]=='-'){
zf = -1;
}
if(ch[i]>='0'&&ch[i]<='9'){
if(dl[j]==null){
dl[j] = new Double(Double.parseDouble(String.valueOf(ch[i])))*zf;
zf=1;
}
else{
if(cx){
dl[j]=dl[j]+Double.parseDouble(String.valueOf(ch[i]))/(10*count);
count*=10;
}
else{
dl[j]=dl[j]*10+Double.parseDouble(String.valueOf(ch[i]));
}
}
}
else if(ch[i]=='.'){
cx=true;
}
else if(i>0){
ys[j]=ch[i];
j++;
cx = false;
count = 1;
}
}
//到这里,运算符和数字应该已经分别存储了
//按顺序运算,和优先级无关
for(int i=0;i<ys.length;i++){
switch(ys[i]){
case '*':
dl[0]=dl[0]*dl[i+1];
break;
case '/':
dl[0]=dl[0]/dl[i+1];
break;
case '+':
dl[0]=dl[0]+dl[i+1];
break;
case '-':
dl[0]=dl[0]-dl[i+1];
break;
}
}
System.out.println(dl[0]);
tf.setText(dl[0].toString());
}
else{
tf.setText(tf.getText()+str);
}
}
};
Button[] btns = new Button[16];
String[] names = {"7","8","9","/","4","5","6","*","1","2","3","-","0",".","+","="};
for(int i=0;i<names.length;i++){
btns[i] = new Button(names[i]);
btns[i].addActionListener(action);
p.add(btns[i]);
}
f.add(p,"Center");
Button btn = new Button("清空");
btn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
tf.setText("");
}
});
f.add(btn,"South");
f.setSize(220,200);
f.setVisible(true);
}
}