一段简单的手写Java计算器代码
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.lang.*;
public class Calculator1 extends JFrame implements ActionListener {
JTextField text;
static boolean isFirst = true;
double number = 0.0;
public static String s = "0";
double value,sum;
int n;
//主函数
public static void main(String[] args){
new Calculator1();
}
//构造方法
public Calculator1(){
JFrame mywindow = new JFrame();
mywindow.setTitle("我的计算器V-1");
mywindow.setSize(250,250);
mywindow.setLocation(400,300);
mywindow.setResizable(false);
mywindow.setLayout(new BorderLayout());
JPanel panel1 = new JPanel(new FlowLayout());
JPanel panel2 = new JPanel(new GridLayout(4, 4));
text = new JTextField("0",20);
text.setEditable(false);
panel1.add(text);
mywindow.add("North", panel1);
mywindow.add("Center", panel2);
String[] array = {"7","8","9","C","4","5","6","+","1","2","3","-","0","*","/","="};
JButton[] buttons = new JButton[array.length];
for(int i=0;i<array.length;i++){
buttons[i] = new JButton(array[i]);
panel2.add(buttons[i]);
}
for(int i=0;i<buttons.length;i++){
buttons[i].addActionListener(this);
}
mywindow.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String oldstr = text.getText();
String label = e.getActionCommand();
if(label.equals("C")){
s="0";
value= 0;
sum = 0;
text.setText(s);
}
else if("+-*/=0123456789".indexOf(label) > 4){
handNumber(label);
}else{
handOperator(label);
}
}
//操作数字函数
public void handNumber(String num){
if(s.equals("0"))
s = num;
else
s = s + num;
text.setText(s);
}
//操作符号函数
public void handOperator(String operator){
value = Double.valueOf(s);
switch(n)
{
case 0:sum = value;break;
case 1:sum = sum + value;break;
case 2:sum = sum - value;break;
case 3:sum = sum * value;break;
case 4:sum = sum / value;break;
}
if(operator.equals("=")){n = 0;}
if(operator.equals("+")){n = 1;}
if(operator.equals("-")){n = 2;}
if(operator.equals("*")){n = 3;}
if(operator.equals("/")){n = 4;}
s = String.valueOf(sum);
if(operator.equals("=")){
text.setText(s);
} else{
text.setText(s+operator);
s= "0";
}
}
}