欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java编写计算器的常见方法实例总结

程序员文章站 2024-03-11 13:25:13
本文实例总结了java编写计算器的常见方法。分享给大家供大家参考,具体如下: 方法一: package wanwa; import java.awt.*;...

本文实例总结了java编写计算器的常见方法。分享给大家供大家参考,具体如下:

方法一:

package wanwa;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class calculator extends jframe {
private container container;
private gridbaglayout layout;
private gridbagconstraints constraints;
private jtextfield displayfield;// 计算结果显示区
private string lastcommand;// 保存+,-,*,/,=命令
private double result;// 保存计算结果
private boolean start;// 判断是否为数字的开始
public calculator() {
super("calculator");
container = getcontentpane();
layout = new gridbaglayout();
container.setlayout(layout);
constraints = new gridbagconstraints();
start = true;
result = 0;
lastcommand = "=";
displayfield = new jtextfield(20);
displayfield.sethorizontalalignment(jtextfield.right);
constraints.gridx = 0;
constraints.gridy = 0;
constraints.gridwidth = 4;
constraints.gridheight = 1;
constraints.fill = gridbagconstraints.both;
constraints.weightx = 100;
constraints.weighty = 100;
layout.setconstraints(displayfield, constraints);
container.add(displayfield);
actionlistener insert = new insertaction();
actionlistener command = new commandaction();
// addbutton("backspace", 0, 1, 2, 1, insert);
// addbutton("ce", 2, 1, 1, 1, insert);
// addbutton("c", 3, 1, 1, 1, insert);
addbutton("7", 0, 2, 1, 1, insert);
addbutton("8", 1, 2, 1, 1, insert);
addbutton("9", 2, 2, 1, 1, insert);
addbutton("/", 3, 2, 1, 1, command);
addbutton("4", 0, 3, 1, 1, insert);
addbutton("5", 1, 3, 1, 1, insert);
addbutton("6", 2, 3, 1, 1, insert);
addbutton("*", 3, 3, 1, 1, command);
addbutton("1", 0, 4, 1, 1, insert);
addbutton("2", 1, 4, 1, 1, insert);
addbutton("3", 2, 4, 1, 1, insert);
addbutton("-", 3, 4, 1, 1, command);
addbutton("0", 0, 5, 1, 1, insert);
// addbutton("+/-", 1, 5, 1, 1, insert);// 只显示"-"号,"+"没有实用价值
addbutton(".", 2, 5, 1, 1, insert);
addbutton("+", 3, 5, 1, 1, command);
addbutton("=", 0, 6, 4, 1, command);
this.setresizable(false);
setsize(180, 200);
setvisible(true);
}
private void addbutton(string label, int row, int column, int with,
int height, actionlistener listener) {
jbutton button = new jbutton(label);
constraints.gridx = row;
constraints.gridy = column;
constraints.gridwidth = with;
constraints.gridheight = height;
constraints.fill = gridbagconstraints.both;
button.addactionlistener(listener);
layout.setconstraints(button, constraints);
container.add(button);
}
private class insertaction implements actionlistener {
public void actionperformed(actionevent event) {
string input = event.getactioncommand();
if (start) {
displayfield.settext("");
start = false;
if (input.equals("+/-"))
displayfield.settext(displayfield.gettext() + "-");
}
if (!input.equals("+/-")) {
  if (input.equals("backspace")) {
   string str = displayfield.gettext();
if (str.length() > 0)
  displayfield.settext(str.substring(0, str.length() - 1));
} else if (input.equals("ce") || input.equals("c")) {
displayfield.settext("0");
start = true;
} else
displayfield.settext(displayfield.gettext() + input);
}
}
}
private class commandaction implements actionlistener {
 public void actionperformed(actionevent evt) {
 string command = evt.getactioncommand();
 if (start) {
 lastcommand = command;
 } else {
 calculate(double.parsedouble(displayfield.gettext()));
 lastcommand = command;
 start = true;
 }
}
}
public void calculate(double x) {
if (lastcommand.equals("+"))
result += x;
else if (lastcommand.equals("-"))
result -= x;
else if (lastcommand.equals("*"))
result *= x;
else if (lastcommand.equals("/"))
result /= x;
else if (lastcommand.equals("="))
result = x;
displayfield.settext("" + result);
}
public static void main(string[] args) {
calculator calculator = new calculator();
calculator.setdefaultcloseoperation(jframe.exit_on_close);
}
}

方法二:

import java.awt.*;
import java.awt.event.*;
public class mycalculator {
 private frame f;
 private textfield tf = new textfield(30);
 private long result;
 private boolean append=false;
 private char operator='=';
 private button[] btn=new button[15];
 public mycalculator() {
  initcomponent();
 }
 private void initcomponent() {
  f = new frame("my calculator v1.0");
  f.setlayout(new borderlayout()); //the frame uses borderlayout
  f.addwindowlistener(new windowadapter() {
   public void windowclosing(windowevent evt) {
    system.exit(0);
   }
  });
  panel centerpanel = new panel();
  centerpanel.setlayout(new gridlayout(5, 3)); //the panel uses gridlayout
  numberlistener nl=new numberlistener();
  operatorlistener ol=new operatorlistener();
  btn[10]=new button("+");
  btn[11]=new button("-");
  btn[12]=new button("*");
  btn[13]=new button("/");
  btn[14]=new button("=");
  for (int i=0;i<=9;i++){
   btn[i]=new button(string.valueof(i));
   centerpanel.add(btn[i]);
   btn[i].addactionlistener(nl);
   if (i%2==1){
    centerpanel.add(btn[(i+19)/2]);
    btn[(i+19)/2].addactionlistener(ol);
   }
  }
  f.add(centerpanel, borderlayout.center);
  panel northpanel = new panel();
  tf.seteditable(false);
  northpanel.add(tf);
  f.add(northpanel, borderlayout.north);
 }
 public void go() {
  f.pack();
  f.setvisible(true);
 }
 public static void main(string[] args) {
  new mycalculator().go();
 }
 /**
 *采用成员内部类方式,实现监听器接口,方便访问主类内类内部成员。
 *此类负责数字按钮action事件监听和处理
 */
 class numberlistener implements actionlistener{
  public void actionperformed(actionevent e){
   if (!append) {
    tf.settext("");
    append=true;
   }
   string s=tf.gettext();
   s+=e.getactioncommand();
   tf.settext(s);
   if (!btn[10].isenabled()){
    for(int i=10;i<=14;i++) btn[i].setenabled(true);
   }
  }
 }
 /**
 * 成员内部类,负责操作符按钮的事件处理
 */
 class operatorlistener implements actionlistener{
  public void actionperformed(actionevent e){
   if (!append) return;
   for(int i=10;i<=14;i++) btn[i].setenabled(false);
   string s=tf.gettext();
   long num=long.parselong(s);//get the number of textfield
   append=false; //set append
   switch(operator){
    case '+':result+=num;break;
    case '-':result-=num;break;
    case '*':result*=num;break;
    case '/':{
     if (num==0) result=0;
     else result/=num;
     break;
    }
    case '=':result=num;break;
   }
   tf.settext(string.valueof(result));
   //set the value of result to textfield
   string op=e.getactioncommand();
   operator=op.charat(0); // set operator
  }
 }
}

方法三:

package wanwa;
import java.util.*;
public class calc {
public static void main(string[] args) {
scanner input = new scanner(system.in);
system.out.println("*****************简易计算器****************");
system.out.println("*\t\t\t\t\t*");
system.out.println("* 使用说明: 1.加法 2.减法 3.乘法 4.除法 *");
system.out.println("*\t\t\t\t\t*");
system.out.println("*****************************************");
for(int i=0;i<100;i++){
system.out.print("\n请选择运算规则:");
int num = input.nextint();
switch(num){
case 1:
system.out.println("\n******你选择了加法******\n");
system.out.print("请输入第1个加数:");
int jiashu1 = input.nextint();
system.out.print("请输入第2个加数:");
int jiashu2 = input.nextint();
system.out.println("运算结果为:" + jiashu1 + " + " + jiashu1 + " = " + (jiashu1 + jiashu2));
break;
case 2:
system.out.println("\n******你选择了减法******\n");
system.out.print("请输入被减数:");
int jianshu1 = input.nextint();
system.out.print("请输入减数:");
int jianshu2 = input.nextint();
system.out.println("运算结果为:" + jianshu1 + " - " + jianshu2 + " = " + (jianshu1 - jianshu2));
break;
case 3:
system.out.println("\n******你选择了乘法******\n");
system.out.print("请输入第1个因数:");
int chengfa1 = input.nextint();
system.out.print("请输入第2个因数:");
int chengfa2 = input.nextint();
system.out.println("运算结果为:" + chengfa1 + " * " + chengfa2 + " = " + (chengfa1 * chengfa2));
break;
case 4:
system.out.println("\n******你选择了除法******\n");
system.out.print("请输入被除数:");
double chufa1 = input.nextint();
system.out.print("请输入除数:");
double chufa2 = input.nextint();
system.out.println("运算结果为:" + chufa1 + " / " + chufa2 + " = " + (chufa1 / chufa2) + " 余 " + (chufa1 % chufa2));
break;
default:
system.out.println("\n你的选择有错,请重新选择!");
break;
}
}
}
}

方法四:

package wanwa;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class calculator extends jframe {
private container container;
private gridbaglayout layout;
private gridbagconstraints constraints;
private jtextfield displayfield;// 计算结果显示区
private string lastcommand;// 保存+,-,*,/,=命令
private double result;// 保存计算结果
private boolean start;// 判断是否为数字的开始
public calculator() {
super("calculator");
container = getcontentpane();
layout = new gridbaglayout();
container.setlayout(layout);
constraints = new gridbagconstraints();
start = true;
result = 0;
lastcommand = "=";
displayfield = new jtextfield(20);
displayfield.sethorizontalalignment(jtextfield.right);
constraints.gridx = 0;
constraints.gridy = 0;
constraints.gridwidth = 4;
constraints.gridheight = 1;
constraints.fill = gridbagconstraints.both;
constraints.weightx = 100;
constraints.weighty = 100;
layout.setconstraints(displayfield, constraints);
container.add(displayfield);
actionlistener insert = new insertaction();
actionlistener command = new commandaction();
// addbutton("backspace", 0, 1, 2, 1, insert);
// addbutton("ce", 2, 1, 1, 1, insert);
// addbutton("c", 3, 1, 1, 1, insert);
addbutton("7", 0, 2, 1, 1, insert);
addbutton("8", 1, 2, 1, 1, insert);
addbutton("9", 2, 2, 1, 1, insert);
addbutton("/", 3, 2, 1, 1, command);
addbutton("4", 0, 3, 1, 1, insert);
addbutton("5", 1, 3, 1, 1, insert);
addbutton("6", 2, 3, 1, 1, insert);
addbutton("*", 3, 3, 1, 1, command);
addbutton("1", 0, 4, 1, 1, insert);
addbutton("2", 1, 4, 1, 1, insert);
addbutton("3", 2, 4, 1, 1, insert);
addbutton("-", 3, 4, 1, 1, command);
addbutton("0", 0, 5, 1, 1, insert);
// addbutton("+/-", 1, 5, 1, 1, insert);// 只显示"-"号,"+"没有实用价值
addbutton(".", 2, 5, 1, 1, insert);
addbutton("+", 3, 5, 1, 1, command);
addbutton("=", 0, 6, 4, 1, command);
this.setresizable(false);
setsize(180, 200);
setvisible(true);
}
private void addbutton(string label, int row, int column, int with,
int height, actionlistener listener) {
jbutton button = new jbutton(label);
constraints.gridx = row;
constraints.gridy = column;
constraints.gridwidth = with;
constraints.gridheight = height;
constraints.fill = gridbagconstraints.both;
button.addactionlistener(listener);
layout.setconstraints(button, constraints);
container.add(button);
}
private class insertaction implements actionlistener {
public void actionperformed(actionevent event) {
string input = event.getactioncommand();
if (start) {
displayfield.settext("");
start = false;
if (input.equals("+/-"))
displayfield.settext(displayfield.gettext() + "-");
}
if (!input.equals("+/-")) {
  if (input.equals("backspace")) {
   string str = displayfield.gettext();
if (str.length() > 0)
  displayfield.settext(str.substring(0, str.length() - 1));
} else if (input.equals("ce") || input.equals("c")) {
displayfield.settext("0");
start = true;
} else
displayfield.settext(displayfield.gettext() + input);
}
}
}
private class commandaction implements actionlistener {
 public void actionperformed(actionevent evt) {
 string command = evt.getactioncommand();
 if (start) {
 lastcommand = command;
 } else {
 calculate(double.parsedouble(displayfield.gettext()));
 lastcommand = command;
 start = true;
 }
}
}
public void calculate(double x) {
if (lastcommand.equals("+"))
result += x;
else if (lastcommand.equals("-"))
result -= x;
else if (lastcommand.equals("*"))
result *= x;
else if (lastcommand.equals("/"))
result /= x;
else if (lastcommand.equals("="))
result = x;
displayfield.settext("" + result);
}
public static void main(string[] args) {
calculator calculator = new calculator();
calculator.setdefaultcloseoperation(jframe.exit_on_close);
}
} 

希望本文所述对大家java程序设计有所帮助。