如何用java做一个计算器,请各位伸出援助之手,小女子感激不尽。
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何用java做一个计算器,请各位伸出援助之手,小女子感激不尽。相关的知识,希望对你有一定的参考价值。
package lab5;public class Calculate
double op1 = 0;
double op2 = 0;
double rgst = 0;
double result = 0;
String curStr = "";
Operator op = Operator.ADD;
CalculatorView calView = null;
public Calculate(CalculatorView view)
op1 = 0;
op2 = 0;
curStr = "0";
rgst = 0;
op = Operator.ADD;
calView = view;
public void clear()
op1 = 0;
op2 = 0;
curStr = "0.0";
op = Operator.ADD;
calView.repaint();
/********************************************/
package lab5;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
public class CalculateController implements ActionListener
boolean digInputListener = false;
double data = 0;
String digStr = "";
String curStr = "";
CalculatorView calView = null;
Calculate cal = null;
CalculateState curCalState = null;
public static HashMap<String, Operator> operatorMap;
operatorMap = new HashMap<String, Operator>();
for (Operator p : Operator.values())
String str = p.toString();
operatorMap.put(str, p);
public CalculateController()
public void setCalculate(Calculate c)
cal = c;
curCalState = new InitCalculateState(this, cal);
public void addCalculateView(CalculatorView view)
calView = view;
public Calculate getCalculate()
return cal;
private void startDigInputListener()
digInputListener = true;
data = 0;
digStr = "";
private void endDigInputListener()
try
digInputListener = false;
data = Double.parseDouble(digStr);
catch (NumberFormatException e)
cal.clear();
cal.setResult(0.0);
private void digInputListener(char d)
digStr += d;
curStr = digStr;
cal.SetCurStr(digStr);
public void changeState(CalculateState newState)
curCalState = newState;
public void actionPerformed(ActionEvent e)
String str = e.getActionCommand();
char firstChar = str.charAt(0);
if ((firstChar <= '9' && firstChar >= '0') || firstChar == '.')
if (digInputListener == false)
startDigInputListener();
digInputListener(firstChar);
else
if (digInputListener == true)
endDigInputListener();
curCalState.inputD(data);
Operator op = operatorMap.get(str);
passMessage(op);
private void passMessage(Operator op)
switch (op)
case ADD:
case SUB:
case MUL:
case DIV:
curCalState.inputB(op);
break;
case COS:
case SIN:
case TAN:
curCalState.inputU(op);
break;
case ASSIGN:
curCalState.inputA();
break;
case CE:
curCalState.inputCE();
break;
case MR:
curCalState.inputMR();
break;
case M:
curCalState.inputM();
break;
case MC:
curCalState.inputMC();
break;
case MS:
curCalState.inputMS();
break;
public CalculatorView getCalculatorView()
return calView;
public static void main(String[] args)
CalculateController calController = new CalculateController();
CalculatorView mainView = new CalculatorView("Calculator",
calController);
Calculate cal = new Calculate(mainView);
calController.setCalculate(cal);
calController.addCalculateView(mainView);
****************************************************
package lab5;
public abstract class CalculateState
protected CalculateController calController;
protected Calculate cal;
public CalculateState(CalculateController controller, Calculate c)
calController = controller;
cal = c;
public void inputA()
void inputD(double d)
void inputU(Operator op)
void inputB(Operator op)
void inputCE()
cal.clear();
/*
* 要存储显示的数据,请单击“MS”。
* 要重新调用存储的数据,请单击“MR”。
* 要清除内存,请单击“MC”。
* 把所显示的数字与内存中的数字相加,请单击“M+”
*/
void inputM()
double curData = calController.getCalculatorView().getMainScreenData();
cal.setRgst(cal.getRgst() + curData);
void inputMR()
inputD(cal.getRgst());
void inputMC()
cal.setRgst(0);
void inputMS()
double curData = calController.getCalculatorView().getMainScreenData();
cal.setRgst(curData);
******************************
package lab5;
import java.awt.*;
import javax.swing.*;
public class CalculatorView extends JFrame
final static long serialVersionUID = 20000;
final int NUM = 24;
JButton[] buttons;
String[] texts = "CE", "MC", "0", "1", "2", "+", "sin", "MR", "3", "4",
"5", "-", "cos", "MS", "6", "7", "8", "*", "tan", "M+", "9", ".",
"=", "/" ;
JTextField rgstScreen;
JTextField mainScreen;
JPanel buttonPanel;
JPanel textPanel;
CalculateController calController = null;
public CalculatorView(String title, CalculateController controller)
super(title);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JFrame.setDefaultLookAndFeelDecorated(true);
calController = controller;
rgstScreen = new JTextField("0.0", 10);
mainScreen = new JTextField("0.0", 20);
rgstScreen.setEditable(false);
mainScreen.setFocusable(false);
textPanel = new JPanel();
textPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
textPanel.add(rgstScreen);
textPanel.add(mainScreen);
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 6));
buttons = new JButton[NUM];
for (int i = 0; i < NUM; i++)
buttons[i] = new JButton(texts[i]);
buttons[i].addActionListener(calController);
buttons[i].setActionCommand(texts[i]);
buttonPanel.add(buttons[i]);
this.getContentPane().add(textPanel);
add(textPanel, BorderLayout.NORTH);
add(buttonPanel, BorderLayout.SOUTH);
pack();
setVisible(true);
public double getMainScreenData()
return Double.parseDouble(mainScreen.getText());
public void repaint()
super.repaint();
Calculate cal = calController.getCalculate();
mainScreen.setText(cal.getCurStr());
rgstScreen.setText(Double.toString(cal.getRgst()));
*************************************
package lab5;
public class InitCalculateState extends CalculateState
public InitCalculateState(CalculateController controller, Calculate c)
super(controller, c);
public void inputD(double d)
OnlyOp1 s = new OnlyOp1(calController, cal);
calController.changeState(s);
s.inputD(d);
class OnlyOp1 extends CalculateState
public OnlyOp1(CalculateController controller, Calculate c)
super(controller, c);
public void inputA()
public void inputD(double d)
calController.getCalculate().setOp1(d);
calController.getCalculate().SetCurStr(Double.toString(d));
public void inputU(Operator op)
UniqueOpState u = new UniqueOpState(calController, cal);
//cal.setOp(op);
calController.changeState(u);
u.inputU(op);
public void inputB(Operator op)
WaitOp2 b = new WaitOp2(calController, cal);
calController.getCalculate().setOp(op);
calController.changeState(b);
class UniqueOpState extends CalculateState
public UniqueOpState(CalculateController controller, Calculate c)
super(controller, c);
public void inputA()
dothing();
public void inputD(double d)
OnlyOp1 w = new OnlyOp1(calController, cal);
calController.changeState(w);
w.inputD(d);
public void inputU(Operator op)
cal.setOp(op);
dothing();
public void inputB(Operator op)
WaitOp2 wOp2 = new WaitOp2(calController, cal);
cal.setOp(op);
calController.changeState(wOp2);
private void dothing()
try
double op1 = cal.result();
cal.setOp1(op1);
cal.SetCurStr(Double.toString(op1));
catch (Exception e)
cal.clear();
cal.setResult(0.0);
cal.SetCurStr("异常!");
class WaitOp2 extends CalculateState
public WaitOp2(CalculateController controller, Calculate c)
super(controller, c);
public void inputA()
try
double op2 = cal.getOp1();
cal.setOp2(op2);
double result = cal.result();
cal.setResult(result);
cal.setOp1(result);
cal.SetCurStr(Double.toString(result));
HaveOp2 b = new HaveOp2(calController, cal);
calController.changeState(b);
catch (Exception e)
cal.clear();
cal.setResult(0.0);
cal.SetCurStr("异常!");
public void inputD(double d)
try
cal.setOp2(d);
cal.SetCurStr(Double.toString(d));
cal.setResult(cal.result());
HaveOp2 b = new HaveOp2(calController, cal);
calController.changeState(b);
catch (Exception e)
cal.clear();
cal.setResult(0.0);
public void inputU(Operator op)
UniqueOpState u = new UniqueOpState(calController, cal);
calController.changeState(u);
u.inputU(op);
public void inputB(Operator op)
cal.setOp(op);
class HaveOp2 extends CalculateState
public HaveOp2(CalculateController controller, Calculate c)
super(controller, c);
public void inputA()
try
double result = cal.result();
cal.setResult(result);
cal.setOp1(result);
cal.SetCurStr(Double.toString(result));
catch (Exception e)
cal.clear();
cal.setResult(0.0);
public void inputD(double d)
OnlyOp1 w = new OnlyOp1(calController, cal);
calController.changeState(w);
w.inputD(d);
public void inputU(Operator op)
UniqueOpState u = new UniqueOpState(calController, cal);
calController.changeState(u);
u.inputU(op);
public void inputB(Operator op)
WaitOp2 w = new WaitOp2(calController, cal);
double result = cal.getResult();
cal.setOp1(result);
cal.setOp(op);
cal.SetCurStr(Double.toString(result));
calController.changeState(w);
******************************
package lab5;
public enum Operator
ADD, SUB, MUL, DIV, COS, SIN, TAN, CE, MR, MC, MS, M, ASSIGN;
public String toString()
switch (this)
case ADD:
return "+";
case SUB:
return "-";
case DIV:
return "/";
case MUL:
return "*";
case COS:
return "cos";
case SIN:
return "sin";
case TAN:
return "tan";
case CE:
return "CE";
case MR:
return "MR";
case MC:
return "MC";
case MS:
return "MS";
case M:
return "M+";
case ASSIGN:
return "=";
default:
return "Unkown Operator";
public static int OperatorType(Operator op)
int type = 0;
switch (op)
case ADD:
case SUB:
case MUL:
case DIV:
type = 2;
break;
case COS:
case SIN:
case TAN:
type = 1;
break;
default:
type = 3;
break;
return type;
public String getCurStr()
return curStr;
public void SetCurStr(String str)
curStr = str;
calView.repaint();
public void setOp1(double d)
op1 = d;
calView.repaint();
public void setOp2(double d)
op2 = d;
calView.repaint();
public void setOp(Operator p)
op = p;
calView.repaint();
public void setResult(double result)
this.result = result;
public double getOp1()
return op1;
public double getOp2()
return op2;
public Operator getOp()
return op;
public double getResult()
return result;
public double result() throws Exception
double ret = 0;
switch (op)
case ADD:
ret = op1 + op2;
break;
case SUB:
ret = op1 - op2;
break;
case MUL:
ret = op1 * op2;
break;
case DIV:
ret = op1 / op2;
break;
case SIN:
ret = Math.sin(op1);
break;
case COS:
ret = Math.cos(op1);
break;
case TAN:
ret = Math.tan(op1);
break;
return ret;
public double getRgst()
return rgst;
public void setRgst(double m)
this.rgst = m;
calView.repaint();
参考技术A import java.awt.*;
import java.awt.event.*;
public class Homework2 extends Frame implements ActionListener,KeyListener
Label label;
Button n1,n2,n3,n4,n5,n6,n7,n8,n9,n0,addition,subtraction,multiplication,division,equle,C;
Font f;
char ch;
String regA,regB;
char op;
double sum;
Homework2()
setTitle("简易计算器");
setLayout(null);
regA=new String("");
regB=new String("");
label=new Label("0",Label.RIGHT);
label.setBackground(Color.black);
f=new Font("arial",Font.BOLD,12);
label.setForeground(Color.white);
label.setFont(f);
n1=new Button("1");
n2=new Button("2");
n3=new Button("3");
n4=new Button("4");
n5=new Button("5");
n6=new Button("6");
n7=new Button("7");
n8=new Button("8");
n9=new Button("9");
n0=new Button("0");
addition=new Button("+");
multiplication=new Button("×");
subtraction=new Button("-");
division=new Button("÷");
equle=new Button("=");
C=new Button("C");
add(label);
add(n1);
add(n2);
add(n3);
add(n4);
add(n5);
add(n6);
add(n7);
add(n8);
add(n9);
add(n0);
add(addition);
add(subtraction);
add(multiplication);
add(subtraction);
add(division);
add(equle);
add(C);
n1.addActionListener(this);
n2.addActionListener(this);
n3.addActionListener(this);
n4.addActionListener(this);
n5.addActionListener(this);
n6.addActionListener(this);
n7.addActionListener(this);
n8.addActionListener(this);
n9.addActionListener(this);
n0.addActionListener(this);
addition.addActionListener(this);
subtraction.addActionListener(this);
multiplication.addActionListener(this);
division.addActionListener(this);
equle.addActionListener(this);
C.addActionListener(this);
n1.addKeyListener(this);
n2.addKeyListener(this);
n3.addKeyListener(this);
n4.addKeyListener(this);
n5.addKeyListener(this);
n6.addKeyListener(this);
n7.addKeyListener(this);
n8.addKeyListener(this);
n9.addKeyListener(this);
n0.addKeyListener(this);
addition.addKeyListener(this);
subtraction.addKeyListener(this);
multiplication.addKeyListener(this);
division.addKeyListener(this);
equle.addKeyListener(this);
C.addKeyListener(this);
label.setBounds(30,50,115,25);
n1.setBounds(30,100,25,25);
n2.setBounds(60,100,25,25);
n3.setBounds(90,100,25,25);
n4.setBounds(30,130,25,25);
n5.setBounds(60,130,25,25);
n6.setBounds(90,130,25,25);
n7.setBounds(30,160,25,25);
n8.setBounds(60,160,25,25);
n9.setBounds(90,160,25,25);
n0.setBounds(60,190,25,25);
addition.setBounds(120,100,25,25);
subtraction.setBounds(120,130,25,25);
multiplication.setBounds(120,160,25,25);
division.setBounds(120,190,25,25);
equle.setBounds(90,190,25,25);
C.setBounds(30,190,25,25);
addWindowListener(new WindowAdapter()
public void windowClosing (WindowEvent e)
System.exit(0);
);
setSize(179,250);
setVisible(true);
validate();
public void actionPerformed(ActionEvent e)
if(e.getSource()==n1)
ch='1';
else if(e.getSource()==n2)
ch='2';
else if(e.getSource()==n3)
ch='3';
else if(e.getSource()==n4)
ch='4';
else if(e.getSource()==n5)
ch='5';
else if(e.getSource()==n6)
ch='6';
else if(e.getSource()==n7)
ch='7';
else if(e.getSource()==n8)
ch='8';
else if(e.getSource()==n9)
ch='9';
else if(e.getSource()==n0)
ch='0';
else if(e.getSource()==addition)
ch='+';
else if(e.getSource()==subtraction)
ch='-';
else if(e.getSource()==multiplication)
ch='*';
else if(e.getSource()==division)
ch='/';
else if(e.getSource()==equle)
ch='=';
else if(e.getSource()==C)
ch='c';
processEvent(ch);
public void keyTyped(KeyEvent e)
char ch=e.getKeyChar();
processEvent(ch);
public void keyPressed(KeyEvent e)
public void keyReleased(KeyEvent e)
public void processEvent(char ch)
switch(ch)
case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
regA=regA+ch;
label.setText(regA);
break;
case 'c':case 'C':
regA="";
regB="";
label.setText("0");
break;
case '=':
getAnswer(regA,regB);
label.setText(String.valueOf(sum));
break;
default:
regB=regA;
op=ch;
regA="";
regB=label.getText();
break;
public double getAnswer(String regA,String regB)
double num1,num2;
num1=Double.parseDouble(regA);
num2=Double.parseDouble(regB);
switch(op)
case '+':
sum=num1+num2;
break;
case '-':
sum=num2-num1;
break;
case '*':
sum=num2*num1;
break;
case '/':
sum=num2/num1;
break;
return sum;
public static void main(String args[])
Homework2 hw2=new Homework2();
参考资料:http://hi.baidu.com/lucky%5Fliu/blog/item/7d0673ecc81d17d12e2e2167.html
参考技术B import java.awt.*;import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame
private JButton b1,b2,b3,b4,b5,b6,b7,b8,b9,b0;
private JButton addButton,minButton,mulButton,dilButton,resultButton;
private JButton pointButton,backspackButton,clearButton,oppButton;
private JTextField resultField;
private boolean isFloat = false;
private String ForeScreen = "", BackScreen = "", operateCurrent = "", operatePre="";
public Calculator()
Container c = getContentPane();
c.setLayout(new BorderLayout());
ButtonHandler handler = new ButtonHandler();
JPanel topButtonPanel = new JPanel();
topButtonPanel.setLayout(new GridLayout(1,3));
JPanel topPanel = new JPanel();
topPanel.setLayout(new GridLayout(2,1));
resultField = new JTextField(15);
resultField.setHorizontalAlignment(JTextField.RIGHT);
backspackButton = new JButton("退格");
backspackButton.addActionListener(handler);
clearButton = new JButton("清零");
clearButton.addActionListener(handler);
oppButton = new JButton("+/-");
oppButton.addActionListener(handler);
topButtonPanel.add(backspackButton);
topButtonPanel.add(clearButton);
topButtonPanel.add(oppButton);
topPanel.add(resultField);
topPanel.add(topButtonPanel);
JPanel cenButtonPanel = new JPanel();
cenButtonPanel.setLayout(new GridLayout(4,4));
b1 = new JButton("1");
b1.addActionListener(handler);
cenButtonPanel.add(b1);
b2 = new JButton("2");
b2.addActionListener(handler);
cenButtonPanel.add(b2);
b3 = new JButton("3");
b3.addActionListener(handler);
cenButtonPanel.add(b3);
addButton = new JButton("+");
addButton.addActionListener(handler);
cenButtonPanel.add(addButton);
b4 = new JButton("4");
b4.addActionListener(handler);
cenButtonPanel.add(b4);
b5 = new JButton("5");
b5.addActionListener(handler);
cenButtonPanel.add(b5);
b6 = new JButton("6");
b6.addActionListener(handler);
cenButtonPanel.add(b6);
minButton = new JButton("-");
minButton.addActionListener(handler);
cenButtonPanel.add(minButton);
b7 = new JButton("7");
b7.addActionListener(handler);
cenButtonPanel.add(b7);
b8 = new JButton("8");
b8.addActionListener(handler);
cenButtonPanel.add(b8);
b9 = new JButton("9");
b9.addActionListener(handler);
cenButtonPanel.add(b9);
mulButton = new JButton("*");
mulButton.addActionListener(handler);
cenButtonPanel.add(mulButton);
b0 = new JButton("0");
b0.addActionListener(handler);
cenButtonPanel.add(b0);
pointButton = new JButton(".");
pointButton.addActionListener(handler);
cenButtonPanel.add(pointButton);
resultButton = new JButton("=");
resultButton.addActionListener(handler);
cenButtonPanel.add(resultButton);
dilButton = new JButton("/");
dilButton.addActionListener(handler);
cenButtonPanel.add(dilButton);
c.add(topPanel,BorderLayout.NORTH);
c.add(cenButtonPanel,BorderLayout.CENTER);
pack();
setSize(200,200);
show();
this.setResizable(false);
private class ButtonHandler implements ActionListener
public void actionPerformed(ActionEvent e)
// TODO 自动生成方法存根
//数字健
if(e.getSource()==b0 || e.getSource()==b1 || e.getSource()==b2 ||
e.getSource()==b3 || e.getSource()==b4 || e.getSource()==b5 ||
e.getSource()==b6 || e.getSource()==b7 || e.getSource()==b8 ||
e.getSource()==b9)
ForeScreen += e.getActionCommand();
resultField.setText(ForeScreen);
//小数点
else if(e.getSource()==pointButton && !isFloat)
isFloat = true;
if(ForeScreen.equals(""))
ForeScreen += "0.";
resultField.setText(ForeScreen);
else
ForeScreen += e.getActionCommand();
resultField.setText(ForeScreen);
//清零
else if(e.getSource()==clearButton)
resultField.setText("");
isFloat = false;
ForeScreen = "";
operatePre = "";
operateCurrent = "";
BackScreen = "";
else if(e.getSource()==backspackButton)
isFloat = false;
int len = resultField.getText().length()-1;
if(len >= 0)
ForeScreen = ForeScreen.substring(0,len);
resultField.setText(ForeScreen);
//加减乘除的操作
else if(e.getSource()==addButton || e.getSource()==minButton ||
e.getSource()==mulButton || e.getSource()==dilButton)
isFloat = false;
if(ForeScreen.equals(""))
operatePre = e.getActionCommand();
else
operateCurrent = e.getActionCommand();
operate();
System.out.println(operateCurrent);
//等于号的操作
else if(e.getSource()==resultButton)
operate();
else if(e.getSource()==oppButton)
if(Double.parseDouble(ForeScreen)>0)
ForeScreen = ´-´ + ForeScreen;
else
int len = ForeScreen.length();
ForeScreen = ForeScreen.substring(1,len);
resultField.setText(ForeScreen);
public void operate()
double dFore, dBack;
Double result;
if(operatePre.equals(""))
BackScreen = ForeScreen;
ForeScreen = "";
resultField.setText(BackScreen);
else
dFore = (new Double(ForeScreen)).doubleValue();
dBack = (new Double(BackScreen)).doubleValue();
ForeScreen = "";
BackScreen = resultField.getText();
result = new Double(count(operatePre, dFore, dBack));
resultField.setText(result.toString());
BackScreen = result.toString();
operatePre = operateCurrent;
public double count(String method, double a, double b)
if(method == "+")
return (a + b);
if(method.equals("-"))
return (b - a);
if(method.equals("*"))
return (a * b);
if(method.equals("/"))
return (b / a);
return 0;
public static void main(String[] args)
Calculator app = new Calculator();
app.addWindowListener(
new WindowAdapter()
public void WindowClosing(WindowEvent e)
System.exit(0);
);
本回答被提问者采纳
HDU2188(巴什博奕)
悼念512汶川大地震遇难同胞——选拔志愿者 Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 5614 Accepted Submission(s): 3544 Problem Description 对于四川同胞遭受的灾难,全国人民纷纷伸出援助之手,差点儿每一个省市都派出了大量的救援人员,这当中包括抢险救灾的武警部队。治疗和防疫的医护人员,以及进行心理疏导的心理学专家。依据要求,我校也有一个奔赴灾区救灾的名额。因为广大师生报名踊跃,学校不得不进行选拔来决定最后的人选。经过多轮的考核,形势逐渐明朗,最后的名额将在“林队”和“徐队”之间产生。可是非常巧合。2个人的简历差点儿一模一样,这让主持选拔的8600非常是为难。
无奈,他决定通过捐款来决定两人谁能入选。
选拔规则例如以下: 1、最初的捐款箱是空的; 2、两人轮流捐款,每次捐款额必须为正整数,而且每人每次捐款最多不超过m元(1<=m<=10)。 3、最先使得总捐款额达到或者超过n元(0<n<10000)的一方为胜者。则其能够亲赴灾区服务。
我们知道。两人都非常想入选志愿者名单,而且都是非常聪明的人,假设林队先捐,请你推断谁能入选最后的名单? Input 输入数据首先包括一个正整数C。表示包括C组測试用例,然后是C行数据,每行包括两个正整数n。m,n和m的含义參见上面提到的规则。
Output 对于每组測试数据,假设林队能入选。请输出字符串"Grass", 假设徐队能入选,请输出字符串"Rabbit",每一个实例的输出占一行。 Sample Input 2 8 10 11 10 Sample Output Grass Rabbit Author lcy
和hdu1846一样裸。
/*********************************************************** > OS : Linux 3.13.0-24-generic (Mint-17) > Author : yaolong > Mail : [email protected] > Time : 2014年10月25日 星期六 11时43分33秒 **********************************************************/ #include <iostream> #include <cstdio> #include <string> #include <cstring> using namespace std; int main() { int n; cin >> n; while ( n-- ) { int a, b; cin >> a >> b; if ( a % ( b + 1 ) == 0 ) { cout << "Rabbit" << endl; } else { cout << "Grass" << endl; } } return 0; }
以上是关于如何用java做一个计算器,请各位伸出援助之手,小女子感激不尽。的主要内容,如果未能解决你的问题,请参考以下文章
如何用table做一个form表单?我新手,请各位大侠帮帮忙,求详解,给小弟个具体代码
python里的爬虫如何使用xpath 提取script里的元素?