给你一个比较简单的吧。以前写的。
创新互联成立于2013年,是专业互联网技术服务公司,拥有项目网站设计制作、成都网站建设网站策划,项目实施与项目整合能力。我们以让每一个梦想脱颖而出为使命,1280元广安做网站,已为上家服务,为广安各地企业和个人服务,联系电话:18980820575
共两个类。还只是完成+、-、×、÷运算而已。
GUI只是用了AWT,很简单,相信一看就能懂了。
Calculator.java
public class Calculator{
private String result = "0";
private int op = 0,add = 1,sub = 2,mul = 3,div = 4;
private double stringToDouble(String x){
double y = Double.parseDouble(x);
return y;
}
private void operate(String x){
double x1 = stringToDouble(x);
double y = stringToDouble(result);
switch (op){
case 0:
result = x;
break;
case 1:
result = String.valueOf(y+x1);
break;
case 2:
result = String.valueOf(y-x1);
break;
case 3:
result = String.valueOf(y*x1);
break;
case 4:
if(x1!=0){
result = String.valueOf(y/x1);
}else{
result = "The divisor can't be zero!";
}
break;
}
}
public String opAdd(String x){
operate(x);
op = add;
return result;
}
public String opSubtract(String x){
operate(x);
op = sub;
return result;
}
public String opMultiply(String x){
operate(x);
op = mul;
return result;
}
public String opDivide(String x){
operate(x);
op = div;
return result;
}
public String opEquals(String x){
operate(x);
op = 0;
return result;
}
public void opClean(){
op = 0;
result = "0";
}
}
CalculatorGUI.java
import java.awt.*;
import java.awt.event.*;
import java.util.EventObject;
public class CalculatorGUI{
private Frame f;
private Panel p1,p2;
private Button b0,b1,b2,b3,b4,b5,b6,b7,b8,b9;
private Button bPoint,bAdd,bDec,bMul,bDiv,bCal;
private TextField tf;
private String s,op;
private Calculator cal = new Calculator();
private boolean ifOp;
public CalculatorGUI(){
f = new Frame("Calculator");
p1 = new Panel();
p2 = new Panel();
b0 = new Button("0");
b1 = new Button("1");
b2 = new Button("2");
b3 = new Button("3");
b4 = new Button("4");
b5 = new Button("5");
b6 = new Button("6");
b7 = new Button("7");
b8 = new Button("8");
b9 = new Button("9");
bPoint = new Button(".");
bAdd = new Button("+");
bDec = new Button("-");
bMul = new Button("*");
bDiv = new Button("/");
bCal = new Button("=");
tf = new TextField(25);
tf.setEditable(false);
}
public void launchFrame(){
f.setSize(220,160);
f.setResizable(false);
f.addWindowListener(new myWindowListener());
p1.setLayout(new FlowLayout(FlowLayout.CENTER));
p1.add(tf);
f.add(p1,BorderLayout.NORTH);
p2.setLayout(new GridLayout(4,4));
b0.addActionListener(new setLabelText_ActionListener());
b1.addActionListener(new setLabelText_ActionListener());
b2.addActionListener(new setLabelText_ActionListener());
b3.addActionListener(new setLabelText_ActionListener());
b4.addActionListener(new setLabelText_ActionListener());
b5.addActionListener(new setLabelText_ActionListener());
b6.addActionListener(new setLabelText_ActionListener());
b7.addActionListener(new setLabelText_ActionListener());
b8.addActionListener(new setLabelText_ActionListener());
b9.addActionListener(new setLabelText_ActionListener());
bPoint.addActionListener(new setLabelText_ActionListener());
bAdd.addActionListener(new setOperator_ActionListener());
bDec.addActionListener(new setOperator_ActionListener());
bMul.addActionListener(new setOperator_ActionListener());
bDiv.addActionListener(new setOperator_ActionListener());
bCal.addActionListener(new setOperator_ActionListener());
p2.add(b7);
p2.add(b8);
p2.add(b9);
p2.add(bAdd);
p2.add(b4);
p2.add(b5);
p2.add(b6);
p2.add(bDec);
p2.add(b1);
p2.add(b2);
p2.add(b3);
p2.add(bMul);
p2.add(b0);
p2.add(bPoint);
p2.add(bCal);
p2.add(bDiv);
f.add(p2,BorderLayout.SOUTH);
f.setVisible(true);
}
public void setTextFieldText_Temp(){
if (tf.getText().length()15 (tf.getText().indexOf(".")==-1 || !s.equals("."))){
tf.setText(tf.getText()+s);
}else{
tf.setText((tf.getText()+s).substring(0,15));
}
}
public void setTextFieldText(){
if(ifOp){
ifOp = false;
tf.setText("");
setTextFieldText_Temp();
}else{
setTextFieldText_Temp();
}
}
public static void main(String[] args){
CalculatorGUI calculator = new CalculatorGUI();
calculator.launchFrame();
}
class myWindowListener extends WindowAdapter{
public void windowClosing(WindowEvent e){
System.exit(0);
}
}
class setLabelText_ActionListener implements ActionListener{
public void actionPerformed(ActionEvent e){
Button tempB = (Button)e.getSource();
s = tempB.getLabel();
setTextFieldText();
}
}
class setOperator_ActionListener implements ActionListener{
public void actionPerformed(ActionEvent e){
Button tempB = (Button)e.getSource();
op = tempB.getLabel();
if(op.equals("+")){
tf.setText(cal.opAdd(tf.getText()));
ifOp = true;
}else if(op.equals("-")){
tf.setText(cal.opSubtract(tf.getText()));
ifOp = true;
}else if(op.equals("*")){
tf.setText(cal.opMultiply(tf.getText()));
ifOp = true;
}else if(op.equals("/")){
tf.setText(cal.opDivide(tf.getText()));
ifOp = true;
}else if(op.equals("=")){
tf.setText(cal.opEquals(tf.getText()));
ifOp = true;
}
}
}
}
主要涉及的知识点: 类的写法, 以及方法的调用 .建议多做练习. 如果有看不懂的地方. 可以继续追问,一起讨论.
参考代码如下
//Number类
class Number {
private int n1;//私有的整型数据成员n1
private int n2;//私有的整型数据成员n2
// 通过构造函数给n1和n2赋值
public Number(int n1, int n2) {
this.n1 = n1;
this.n2 = n2;
}
// 加法
public int addition() {
return n1 + n2;
}
// 减法
public int subtration() {
return n1 - n2;
}
// 乘法
public int multiplication() {
return n1 * n2;
}
// 除法 (可能除不尽,所以使用double作为返回类型)
public double division() {
return n1 * 1.0 / n2; // 通过n1*1.0 把计算结果转换成double类型.
}
}
//Exam4 类
public class Exam4{
public static void main(String[] args) {
Number number=new Number(15, 6);//创建Number类的对象
//下面的是调用方法得到返回值进行输出显示
System.out.println("加法"+number.addition());
System.out.println("减法"+number.subtration());
System.out.println("乘法"+number.multiplication());
System.out.println("除法"+number.division());
}
}
关于计算器的设计其实是一个很大的学问,如果你按照严格的设计来完成一个计算器的话,完成之后。你就是一个很牛的人了。注意我说的是很牛
关于这方面的资料我建议你看本书
《大话设计模式》
这本书就是从计算器来展开的设计模式的运用和讲解
学java的时候自己编的,很简单,能够连续输入计算式后进行计算
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**简易计算器,能够进行简单的计算
*
* @see 2008.12.9
*/
public class CalculatorA
implements ActionListener{
private JFrame frame;
private JTextField field;
private JButton[] allButtons;
private JButton clearButton;
// private JButton backButton;
String result="";//保存结果
StringBuilder sb = new StringBuilder();//保存要进行的计算式
int x = 0; //用来判断上一次的事件类型
String str = "123+456-789*0.=/";
ArrayListString arrayList = new ArrayListString();//保存计算式,通过方法进行运算
public CalculatorA(){
frame = new JFrame("我的计算器v1.1");
frame.setLocation(300,300);
field = new JTextField(25);
allButtons = new JButton[16];
for(int i=0;iallButtons.length;i++){
allButtons[i]= new JButton(str.substring(i,i+1));
}
clearButton = new JButton("CLEAR");
// backButton = new JButton("——");
init();
setFondAndColor();
addEventHander();
}
public void init(){
frame.setLayout(new BorderLayout());
JPanel northPanel = new JPanel();
JPanel centerPanel = new JPanel();
JPanel southPanel = new JPanel();
northPanel.setLayout(new FlowLayout());
centerPanel.setLayout(new GridLayout(4,4));
southPanel.setLayout(new FlowLayout());
northPanel.add(field);
for(int i=0;iallButtons.length;i++){
centerPanel.add(allButtons[i]);
}
southPanel.add(clearButton);
//southPanel.add(backButton);
frame.add(northPanel,BorderLayout.NORTH);
frame.add(centerPanel,BorderLayout.CENTER);
frame.add(southPanel,BorderLayout.SOUTH);
}
//设置输入字体
public void setFondAndColor(){
field.setFont(new Font("宋体",Font.BOLD,24));
field.setBackground(new Color(100,200,200));
field.setForeground(Color.RED);
//设置字体从右起始
field.setHorizontalAlignment(JTextField.RIGHT);
}
public void showMi(){
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void addEventHander(){
for(int i=0;iallButtons.length;i++){
allButtons[i].addActionListener(this);
}
clearButton.addActionListener(this);
// backButton.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
String str = e.getActionCommand();//取得当前事件返回的值
if("0123456789.".indexOf(str)!=-1){
if(x == 0){ //当x为0时表示还没有进行输入
result=str;
sb.append(str);
field.setText(str);
x = 1;
}
else if(x == 1){
result = result +str;
sb.append(str);
field.setText(result);
x = 1;
}
else if(x == 2){
sb.delete(0,sb.length());
result = result+str;
sb.append(str);
field.setText(result);
x = 1;
}
else if(x == 3){
result = str;
sb.delete(0,sb.length());
arrayList.clear();
field.setText(str);
sb.append(str);
field.setText(str);
x = 1;
}
else if(x == 4){
result ="";
sb.delete(0,sb.length());
arrayList.clear();
result = str;
sb.append(str);
field.setText(str);
x = 1;
}
else{
result = result +str;
sb.append(str);
field.setText(result);
x = 1;
}
}
else if("+*-/".indexOf(str)!=-1){
if(x == 0){
field.setText("");
x = 2;
}
else if(x == 1){
result = result + str;
arrayList.add(sb.toString());
arrayList.add(str);
sb.append(str);
field.setText(result);
x = 2;
}
else if(x == 2){
x = 2;
}
else if(x == 3){
field.setText(result+str);
arrayList.add(result);
arrayList.add(str);
result = result+str;
x = 2;
}
else if(x == 4){
result ="";
sb.delete(0,sb.length());
arrayList.clear();
x = 2;
}
else{
field.setText(result+str);
arrayList.add(result);
arrayList.add(str);
result = result+str;
x = 2;
}
}
else if("=".equals(str)){
if(x == 0){
field.setText("0");
arrayList.clear();
result = "0";
x = 3;
}
else if(x == 1){
try{
arrayList.add(sb.toString());
arrayList = getResult(arrayList);
result = arrayList.get(0);
field.setText(result);
arrayList.clear();
x = 3;
}catch(Exception e1){
field.setText("数据格式异常");
x = 0;
}
}
else if(x == 2){
field.setText("数据格式错误.....");
arrayList.clear();
x = 0;
}
else if(x == 3){
field.setText(result);
x = 3;
}
else if(x == 4){
result ="";
sb.delete(0,sb.length());
arrayList.clear();
x = 3;
}
else {
try{
arrayList.add(sb.toString());
arrayList = getResult(arrayList);
result = arrayList.get(0);
field.setText(result);
arrayList.clear();
x = 3;
}catch(Exception e1){
field.setText("数据格式异常");
x = 0;
}
}
}
else if("CLEAR".equals(str)){
arrayList.clear();
field.setText("0");
arrayList.add("0");
x = 4;
}
else{
if(result.length()1){
result = result.substring(0,result.length()-1);
if(sb.length()0){
sb.delete(sb.length()-1,sb.length());
}
else {
sb.delete(0,1);
}
field.setText(result);
x = 5;
}
else{
result = "";
sb.delete(0,sb.length());
arrayList.clear();
field.setText("0");
x = 0;
}
}
}
public static ArrayListString getResult(ArrayListString list){
String res = null;
String[] s = {"/","*","-","+"};
int i=0;
if(list.size()1){
for(;is.length;){
if(s[i].equals("/")){
for(int j=0;jlist.size();j++){
if(list.get(j).equals(s[i])){
res = Double.toString(Double.parseDouble(list.get(j-1))/Double.parseDouble(list.get(j+1)));
//本地的数据格式
NumberFormat nf = NumberFormat.getInstance();
res = nf.format(Double.parseDouble(res));
res = getChange(res);
list.set(j-1,res);
list.remove(j);
list.remove(j);
getResult(list);
}
}
i++;
}
else if(s[i].equals("*")){
for(int j=0;jlist.size();j++){
if(list.get(j).equals(s[i])){
res = Double.toString(Double.parseDouble(list.get(j-1))*Double.parseDouble(list.get(j+1)));
NumberFormat nf = NumberFormat.getInstance();
res = nf.format(Double.parseDouble(res));
res = getChange(res);
list.set(j-1,res);
list.remove(j);
list.remove(j);
getResult(list);
}
}
i++;
}
else if(s[i].equals("-")){
for(int j=0;jlist.size();j++){
if(list.get(j).equals(s[i])){
res = Double.toString(Double.parseDouble(list.get(j-1))-Double.parseDouble(list.get(j+1)));
NumberFormat nf = NumberFormat.getNumberInstance();
res = nf.format(Double.parseDouble(res));
res = getChange(res);
list.set(j-1,res);
list.remove(j);
list.remove(j);
getResult(list);
}
}
i++;
}
else {
for(int j=0;jlist.size();j++){
if(list.get(j).equals(s[i])){
res = Double.toString(Double.parseDouble(list.get(j-1))+Double.parseDouble(list.get(j+1)));
NumberFormat nf = NumberFormat.getInstance();
res = nf.format(Double.parseDouble(res));
res = getChange(res);
list.set(j-1,res);
list.remove(j);
list.remove(j);
getResult(list);
}
}
i++;
}
}
}
return list;
}
//对数字字符串进行排除不必要符号
public static String getChange(String res){
String s_temp = "";
char[] c = new char[res.length()];
for(int k=0;kc.length;k++){
c[k] = res.charAt(k);
}
for(int k=0;kc.length;k++){
if((c[k]= '0' c[k]= '9')|| c[k] == '.'){
s_temp += c[k];
}
}
return s_temp;
}
public static void main(String[] args){
new CalculatorA().showMi();
}
}