您的位置:

java简单计算器,java简单计算器的实现

本文目录一览:

如何用java编写一个简单的计算器,只要能进行最基本的加减乘除运算就可以了,本人急用,简单易懂即可,大

简单的啊,我有个自己编的完美的,不过给你改成简单的吧。有注释。

import java.awt.*;

import javax.swing.*;

import javax.swing.border.*;

import java.awt.event.*;

import java.text.*;

public class Calculator extends JFrame implements ActionListener

{

int m=0,i,n=0;

float sum=0,s1,s2,equ;

String v="";

JPanel delete_main = new JPanel();

JPanel delete = new JPanel();

JPanel buttons = new JPanel();

JTextField text = new JTextField("0");

JButton backspace = new JButton("Backspace");

JButton c = new JButton("C");

JButton ce = new JButton("CE");

JButton bt1= new JButton("1");

JButton bt2= new JButton("2");

JButton bt3= new JButton("3");

JButton bt4= new JButton("+");

JButton bt5 = new JButton("4");

JButton bt6= new JButton("5");

JButton bt7= new JButton("6");

JButton bt8= new JButton("-");

JButton bt9= new JButton("7");

JButton bt10= new JButton("8");

JButton bt11= new JButton("9");

JButton bt12= new JButton("*");

JButton bt13= new JButton("0");

JButton bt14= new JButton(".");

JButton bt15= new JButton("=");

JButton bt16= new JButton("/");

public Calculator()

{

super("简易计算器--超人不会飞荣誉出品");

delete.setLayout(new GridLayout(1, 3, 15, 15));

delete.add(backspace);

delete.add(c);

delete.add(ce);

delete.setBorder(new LineBorder(delete.getBackground(), 5));//添加边框

c.addActionListener(this);

ce.addActionListener(this);

backspace.addActionListener(this);

text.setFont(new Font("宋体", Font.BOLD +Font.ITALIC, 20));

// 设置显示字体

text.setBackground(Color.getHSBColor(44, 3, 87));

text.setBorder(new LineBorder(Color.ORANGE, 1));

text.setHorizontalAlignment(SwingConstants.RIGHT); // 设置鼠标靠右

text.setEditable(false); // 屏蔽键盘输入,防止非法字符

delete_main.setLayout(new GridLayout(2, 1, 10, 10));

delete_main.add(text, BorderLayout.NORTH);

delete_main.add(delete, BorderLayout.SOUTH);

buttons.setLayout(new GridLayout(4, 5, 10, 20));

bt1.addActionListener(this); // 为各个按钮添加事件监听

buttons.add(bt1);

bt2.addActionListener(this);

buttons.add(bt2);

bt3.addActionListener(this);

buttons.add(bt3);

bt4.addActionListener(this);

buttons.add(bt4);

bt5.addActionListener(this);

buttons.add(bt5);

bt6.addActionListener(this);

buttons.add(bt6);

bt7.addActionListener(this);

buttons.add(bt7);

bt8.addActionListener(this);

buttons.add(bt8);

bt9.addActionListener(this);

buttons.add(bt9);

bt10.addActionListener(this);

buttons.add(bt10);

bt11.addActionListener(this);

buttons.add(bt11);

bt12.addActionListener(this);

buttons.add(bt12);

bt13.addActionListener(this);

buttons.add(bt13);

bt14.addActionListener(this);

buttons.add(bt14);

bt15.addActionListener(this);

buttons.add(bt15);

bt16.addActionListener(this);

buttons.add(bt16);

buttons.setBorder(new LineBorder(delete.getBackground(), 5));//边框

this.setLayout(new BorderLayout());

this.add(delete_main, BorderLayout.NORTH);

this.add(buttons, BorderLayout.SOUTH);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //添加关闭窗口事件监听器

pack(); //自动设置窗体大小

setResizable(false); // 设置面板大小不可变

setVisible(true);

Toolkit tk = this.getToolkit();

Dimension de = tk.getScreenSize();

setBounds((de.width - this.getWidth()) / 2,(de.height - this.getHeight()) / 2, this.getWidth(), this.getHeight());

//使之居于屏幕正中央

}

public void actionPerformed(ActionEvent e)

{ //事件响应

//Object source = e.getSource();

if(e.getSource()==backspace) //退格键

{

v=v.substring(0,v.length() - 1);

text.setText(v);

}

if(e.getSource()==c||e.getSource()==ce) //清空键

{

m=0;

sum=0;

v="";s1=0;s2=0;i=0;

text.setText("0");

}

if(e.getSource()==bt1)

{

if(m==1)

v="";

v=v+"1";

text.setText(v);

m=0;n=1;

}

if(e.getSource()==bt2)

{

if(m==1)

v="";

v=v+"2";

text.setText(v);

m=0;n=1;

}

if(e.getSource()==bt3)

{

if(m==1)

v="";

v=v+"3";

text.setText(v);

m=0;n=1;

}

if(e.getSource()==bt4) // +按钮

{

if(n==1) //如果按之前按了0~9数字键,就运算

{

sum=Float.parseFloat(v);

}

else //如果按之前没按0~9数字键,直接按了运算符,不做任何操作

{

}

i=1;

m=1;n=0;

}

if(e.getSource()==bt5)

{

if(m==1)

v="";

v=v+"4";

text.setText(v);

m=0;n=1;

}

if(e.getSource()==bt6)

{

if(m==1)

v="";

v=v+"5";

text.setText(v);

m=0;n=1;

}

if(e.getSource()==bt7)

{

if(m==1)

v="";

v=v+"6";

text.setText(v);

m=0;n=1;

}

if(e.getSource()==bt8) // -按钮

{

if(n==1)

{

sum=Float.parseFloat(v);

}

else

{

}

i=2;

m=1;n=0;

}

if(e.getSource()==bt9)

{

if(m==1)

v="";

v=v+"7";

text.setText(v);

m=0;n=1;

}

if(e.getSource()==bt10)

{

if(m==1)

v="";

v=v+"8";

text.setText(v);

m=0;n=1;

}

if(e.getSource()==bt11)

{

if(m==1)

v="";

v=v+"9";

text.setText(v);

m=0;n=1;

}

if(e.getSource()==bt12) //*按钮

{

if(n==1)

{

sum=Float.parseFloat(v);

}

else

{

}

i=3;

m=1;n=0;

}

if(e.getSource()==bt13)

{

if(m==1)

v="";

v=v+"0";

text.setText(v);

m=0;n=1;

}

if(e.getSource()==bt14)

{

}

if(e.getSource()==bt15) //等于按钮

{

if(m==1) // 如果输入了+=等非法输入,不做任何操作

{ }

else

{

s1=sum;

s2=Float.parseFloat(v);

switch(i)

{

case 0: //如果按过数字键后直接按等号,直接输出

equ=Float.parseFloat(v);

break;

case 1:

equ=s1+s2;

break;

case 2:

equ=s1-s2;

break;

case 3:

equ=s1*s2;

break;

case 4:

equ=s1/s2;

break;

}

sum=0;v=""; //清空运算数

v=String.valueOf(equ);

text.setText(String.valueOf(equ));

i=0;

}

}

if(e.getSource()==bt16) // 除按钮

{

if(n==1)

{

sum=Float.parseFloat(v);

}

else

{

}

i=4;

m=1;n=0;

}

}

public static void main(String[] args)

{

Calculator bt=new Calculator();

}

}

JAVA 编写计算器 要代码最简单的

学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();

}

}

求JAVA编写的 简易计算器程序,附上注释

1、首先准备好软件即eclipse和java,下载安装完成后打开eclipse。

2、点击左上角的file 新建一个project。

3、给project取一个名字,其他的选项都是默认然后点击finish。

4、接下来是新建一个class。

5、在给class取名字的时候注意用英文名的首字母要大写。完成后点击finish。

6、这就是开始写代码的工作台,将代码写在绿字下。

7、这就是第一个hello world程序。

如何用java写一个简单的计算器

import java.awt.Button;

import java.awt.Color;

import java.awt.Frame;

import java.awt.GridLayout;

import java.awt.Panel;

import java.awt.TextField;

import java.awt.event.MouseEvent;

import java.awt.event.MouseListener;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

public class Calculator extends WindowAdapter implements MouseListener {

private String first;

private String second;

private String operator;

private Button zero = new Button("0");

private Button one = new Button("1");

private Button two = new Button("2");

private Button three = new Button("3");

private Button four = new Button("4");

private Button five = new Button("5");

private Button six = new Button("6");

private Button seven = new Button("7");

private Button eight = new Button("8");

private Button nine = new Button("9");

private Button decimal = new Button(".");

private Button equal = new Button("=");

private Button add = new Button("+");

private Button sub = new Button("-");

private Button mul = new Button("*");

private Button div = new Button("/");

private TextField input = new TextField();

private Button CE = new Button("CE");

private Button DEL = new Button("Del");

public static void main(String[] args) {

new Calculator();

}

public Calculator(){

Frame f = new Frame("Calculator");

f.add("North", input);

Panel keys = new Panel();

f.add(keys, "Center");

keys.setLayout(new GridLayout(4, 4));

keys.add(seven);

keys.add(eight);

keys.add(nine);

keys.add(add);

keys.add(four);

keys.add(five);

keys.add(six);

keys.add(sub);

keys.add(one);

keys.add(two);

keys.add(three);

keys.add(mul);

keys.add(zero);

keys.add(decimal);

keys.add(equal);

keys.add(div);

zero.addMouseListener(this);

one.addMouseListener(this);

two.addMouseListener(this);

three.addMouseListener(this);

four.addMouseListener(this);

five.addMouseListener(this);

six.addMouseListener(this);

seven.addMouseListener(this);

eight.addMouseListener(this);

nine.addMouseListener(this);

add.addMouseListener(this);

sub.addMouseListener(this);

div.addMouseListener(this);

mul.addMouseListener(this);

equal.addMouseListener(this);

decimal.addMouseListener(this);

Panel addtionalPanel = new Panel();

addtionalPanel.setLayout(new GridLayout(1, 2));

addtionalPanel.add(CE);

addtionalPanel.add(DEL);

CE.setBackground(Color.green);

DEL.setBackground(Color.cyan);

CE.addMouseListener(this);

DEL.addMouseListener(this);

f.add("South", addtionalPanel);

f.addWindowListener(this);

f.setVisible(true);

f.setLocation(200, 300);

f.setSize(200, 200);

}

public void windowClosing(WindowEvent e) {

System.exit(0);

}

public void mouseClicked(MouseEvent e) {

Button btn = (Button) e.getSource();

String key = btn.getActionCommand().trim();

if(btn == one || btn == two || btn == three || btn == zero

|| btn == four || btn == five || btn == six

|| btn == seven || btn == eight || btn == nine){

if(isBlank(operator)){

if(isBlank(first)){

first = key;

}else{

first += key;

}

input.setText(first);

}else{

if(isBlank(second)){

second = key;

}else{

second += key;

}

input.setText(second);

}

}else if(btn == decimal){

if(isBlank(operator)){

if(isBlank(first)){

first = "0.";

input.setText(first);

}else{

if(first.indexOf(".") == -1){

first += ".";

input.setText(first);

}

}

}else{

if(isBlank(second)){

second = "0.";

input.setText(second);

}else{

if(second.indexOf(".") == -1){

second += ".";

input.setText(second);

}

}

}

}else if(btn == equal){

if(!isBlank(second) !isBlank(first) !isBlank(operator)){

double result = 0.0D;

if(operator.equals("+")){

result = Double.parseDouble(first) + Double.parseDouble(second);

}else if(operator.equals("-")){

result = Double.parseDouble(first) - Double.parseDouble(second);

}else if(operator.equals("*")){

result = Double.parseDouble(first) * Double.parseDouble(second);

}else if(operator.equals("/")){

result = Double.parseDouble(first) / Double.parseDouble(second);

}

int value = (int)Math.round(result);

if(value == result){

input.setText(String.valueOf(value));

}else{

input.setText(String.valueOf(result));

}

first = String.valueOf(result);

second = null;

operator = null;

}

}else if(btn == add || btn == sub || btn == div || btn == mul){

if(!isBlank(first)){

if(!isBlank(operator) !isBlank(second)){

if(operator.equals("+")){

first = String.valueOf(Double.parseDouble(first) + Double.parseDouble(second));

}else if(operator.equals("-")){

first = String.valueOf(Double.parseDouble(first) - Double.parseDouble(second));

}else if(operator.equals("*")){

first = String.valueOf(Double.parseDouble(first) * Double.parseDouble(second));

}else if(operator.equals("/")){

first = String.valueOf(Double.parseDouble(first) / Double.parseDouble(second));

}

second = null;

}

operator = key;

}

}else if(btn == CE){

first = null;

second = null;

operator = null;

input.setText(null);

}else if(btn == DEL){

if(isBlank(operator)){

if(!isBlank(first)){

first = first.substring(0, first.length() -1);

input.setText(first);

}

}else{

if(!isBlank(second)){

second = second.substring(0, second.length() -1);

input.setText(second);

}

}

}

}

private boolean isBlank(String str){

return str == null || str.trim().equals("");

}

public void mousePressed(MouseEvent e) {}

public void mouseReleased(MouseEvent e) {}

public void mouseEntered(MouseEvent e) {}

public void mouseExited(MouseEvent e) {}

}

用JAVA编写一个简单的计算器,要求如下

然后 通过输入 显示结果,比如说:

以下是上图计算器的代码:

package Computer;

import java.awt.BorderLayout;

import java.awt.Color;

import java.awt.Container;

import java.awt.Font;

import java.awt.GridLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.util.Stack;

import javax.swing.JApplet;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.JTextField;

public class Count extends JApplet implements ActionListener

{

/**

*

*/

private static final long serialVersionUID = 1L;

private JTextField textField = new JTextField("请输入");

String operator = "";//操作

String input = "";//输入的 式子

boolean flag =  true;

//  boolean flag1 = true;

//  boolean flag2 = true;

public void init()//覆写Applet里边的init方法

{

Container C = getContentPane();

JButton b[] = new JButton[16];

JPanel panel = new JPanel();

C.add(textField, BorderLayout.NORTH);

C.add(panel,BorderLayout.CENTER);

panel.setLayout(new GridLayout(4, 4,5,5));

String name[]={"7","8","9","+","4","5","6","-","1","2","3","*","0","C","=","/"};//设置 按钮

for(int i=0;i16;i++)//添加按钮

{

b[i] = new JButton(name[i]);

b[i].setBackground(new Color(192,192,192));

b[i].setForeground(Color.BLUE);//数字键 设置为 蓝颜色

if(i%4==3)

b[i].setForeground(Color.RED);

b[i].setFont(new Font("宋体",Font.PLAIN,16));//设置字体格式

panel.add(b[i]);

b[i].addActionListener(this);

}

b[13].setForeground(Color.RED);//非数字键,即运算键设置为红颜色

b[13].setForeground(Color.RED);

}

public void actionPerformed(ActionEvent e)

{

int cnt = 0;

String actionCommand = e.getActionCommand();

if(actionCommand.equals("+")||actionCommand.equals("-")||actionCommand.equals("*") ||actionCommand.equals("/"))

input +=" "+actionCommand+" ";//设置输入,把输入的样式改成 需要的样子

else if(actionCommand.equals("C"))

input = "";

else if(actionCommand.equals("="))//当监听到等号时,则处理 input

{

input+= "="+compute(input);

textField.setText(input);

input="";

cnt = 1;

}

else

input += actionCommand;//数字为了避免多位数的输入 不需要加空格

if(cnt==0)

textField.setText(input);

}

private String compute(String input)//即1237 的 样例

{

String str[];

str = input.split(" ");

StackDouble s = new StackDouble();

double m = Double.parseDouble(str[0]);

s.push(m);

for(int i=1;istr.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;

}

public static void main(String args[])

{

JFrame frame = new JFrame("Count");

Count applet = new Count();

frame.getContentPane().add(applet, BorderLayout.CENTER);

applet.init();//applet的init方法

applet.start();//线程开始

frame.setSize(350, 400);//设置窗口大小

frame.setVisible(true);//设置窗口可见

}

}

用Java编写一个简单的计算器程序

import java.awt.*;

import java.awt.event.*;

public class CalcAppDemo extends Frame{

private TextField t_result;

private Panel p_main; //主面板

private Panel p_num; //数字面板

private Panel p_oper; //操作符面板

private Panel p_show; //显示面板

private Button b_num[]; //数字按钮

private Button b_oper[]; //操作符面板

public CalcAppDemo(String title){

setTitle(title);

t_result = new TextField("0.0", 21);

p_main = new Panel();

p_num = new Panel();

p_oper = new Panel();

p_show = new Panel();

p_main.setLayout(new BorderLayout());

p_num.setLayout(new GridLayout(4, 3, 1, 1));

p_oper.setLayout(new GridLayout(4, 2, 1, 1));

b_num = new Button[12];

for(int i=0; i9; i++)

{

b_num[i] = new Button(new Integer(i+1).toString());

}

b_num[9] = new Button("0");

b_num[10] = new Button("cls");

b_num[11] = new Button(".");

for(int i=0; i12; i++)

{

p_num.add(b_num[i]);

}

b_oper = new Button[8];

b_oper[0] = new Button("+");

b_oper[1] = new Button("-");

b_oper[2] = new Button("*");

b_oper[3] = new Button("/");

b_oper[4] = new Button("pow");

b_oper[5] = new Button("sqrt");

b_oper[6] = new Button("+/-");

b_oper[7] = new Button("=");

for(int i=0; i8; i++) //

{

p_oper.add(b_oper[i]);

}

t_result.setEditable(false);

p_show.add(t_result, BorderLayout.NORTH);

p_main.add(p_show, BorderLayout.NORTH);

p_main.add(p_num, BorderLayout.WEST);

p_main.add(p_oper, BorderLayout.EAST);

this.add(p_main, BorderLayout.CENTER);

setSize(400, 400);

setResizable(false);

pack();

this.addWindowListener(new WindowAdapter(){

public void windowClosing(WindowEvent e)

{

System.exit(0);

}

});

ButtonListener b1 = new ButtonListener();

for(int i=0; i12; i++)

{

b_num[i].addActionListener(b1);

}

for(int i=0; i8; i++)

{

b_oper[i].addActionListener(b1);

}

}

class ButtonListener implements ActionListener

{

private String lastOp; //存储上一此操作符

private String strVal; //存储数字对应的字符串

private double total; //总数

private double number; //存储新输入的数

private boolean firsttime; //判断是否第一次按下的是操作符按钮

private boolean operatorPressed;//判断是否已经按过操作符按钮

ButtonListener()

{

firsttime = true;

strVal = "";

}

//事件处理器

public void actionPerformed(ActionEvent e)

{

String s = ((Button)e.getSource()).getLabel().trim();

if(Character.isDigit(s.charAt(0)))

{//判断是操作数还是操作符

handleNumber(s);

}

else

{

calculate(s);

}

}

//判断是一元操作符还是二元操作符,并根据操作符类型做计算

void calculate(String op)

{

operatorPressed = true;

if(firsttime! isUnary(op))

{

total = getNumberOnDisplay();

firsttime = false;

}

if(isUnary(op))

{

handleUnaryOp(op);

}

else if(lastOp != null)

{

handleBinaryOp(lastOp);

}

if(! isUnary(op))

{

lastOp = op;

}

}

//判断是否一元操作符

boolean isUnary(String s)

{

return s.equals("=")

||s.equals("cls")||s.equals("sqrt")

||s.equals("+/-")||s.equals(".");

}

//处理一元操作符

void handleUnaryOp(String op)

{

if(op.equals("+/-"))

{//

number = negate(getNumberOnDisplay() + "");

t_result.setText("");

t_result.setText(number + "");

return;

}else if(op.equals("."))

{

handleDecPoint();

return;

}else if(op.equals("sqrt"))

{

number = Math.sqrt(getNumberOnDisplay());

t_result.setText("");

t_result.setText(number + "");

return;

}else if(op.equals("="))

{//

if(lastOp!= null !isUnary(lastOp))

{

handleBinaryOp(lastOp);

}

lastOp = null;

firsttime = true;

return;

}else

{

clear();

}

}

//处理二元运算符

void handleBinaryOp(String op)

{

if(op.equals("+"))

{

total +=number;

}else if(op.equals("-"))

{

total -=number;

}else if(op.equals("*"))

{

total *=number;

}else if(op.equals("/"))

{

try

{

total /=number;

}catch(ArithmeticException ae){}

}else if(op.equals("pow"))

total = Math.pow(total, number);

//t_result.setText("");

lastOp = null;

// strVal = "";

number = 0;

t_result.setText(total + "");

}

//该方法用于处理数字按钮

void handleNumber(String s)

{

if(!operatorPressed)

{

strVal += s;

}else

{

operatorPressed = false;

strVal = s;

}

//

number = new Double(strVal).doubleValue();

t_result.setText("");

t_result.setText(strVal);

}

//该方法用于按下"."按钮

void handleDecPoint()

{

operatorPressed = false;

//

if(strVal.indexOf(".")0)

{

strVal += ".";

}

t_result.setText("");

t_result.setText(strVal);

}

//该方法用于将一个数求反

double negate(String s)

{

operatorPressed = false;

//如果是一个整数,去掉小数点后面的0

if(number == (int)number)

{

s = s.substring(0,s.indexOf("."));

}

//如果无"-"增加在该数的前面

if(s.indexOf("-")0)

{

strVal = "-" + s;

}

else

{

strVal = s.substring(1);

}

return new Double(strVal).doubleValue();

}

//将显示框中的值转换成Double

double getNumberOnDisplay()

{

return new Double(t_result.getText()).doubleValue();

}

//清除屏幕并设置所有的标识

void clear()

{

firsttime = true;

lastOp = null;

strVal = "";

total = 0;

number = 0;

t_result.setText("0");

}

}

public static void main(String[] args) {

CalcAppDemo c = new CalcAppDemo("简单的计算器程序");

c.setVisible(true);

}

}