java计算器程序代码?java编写简易计算器
大家好,今天来为大家解答java计算器程序代码这个问题的一些问题点,包括java编写简易计算器也一样很多人还不知道,因此呢,今天就来为大家分析分析,现在让我们一起来看看吧!如果解决了您的问题,还望您关注下本站哦,谢谢~
求一简单Java计算器应用程序代码,
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener
{
private boolean dotExist, operated, equaled;//帮助运算的布尔变量
private double storedNumber;//目前的结果
private char lastOperator;//表示上一运算符
private JTextField operation;//结果栏
private JButton dot, plus, minus, multi, div, sqrt, equal, changePN, clear;//运算符
private JButton[] numbers;//数字
//构造者
public Calculator()
{
setTitle("Calculator");
//初始化变量
dotExist= false;//表示当前的数是否有小数点
operated= false;//表示任意运算符是否被按下
equaled= false;//表示等号是否被按下
storedNumber= 0;
lastOperator='?';
//初始化窗口变量
operation= new JTextField("0");
operation.setEditable(false);
numbers= new JButton[10];
for(int i= 0; i< 10; i++)
numbers[i]= new JButton(""+ i);
dot= new JButton(".");
plus= new JButton("+");
minus= new JButton("-");
multi= new JButton("*");
div= new JButton("/");
sqrt= new JButton("√");
equal= new JButton("=");
changePN= new JButton("±");
clear= new JButton("AC");
//将窗口物体放入窗口
GridBagLayout layout= new GridBagLayout();
getContentPane().setLayout(layout);
addComponent(layout, operation, 0, 0, 4, 1);
addComponent(layout, numbers[1], 1, 0, 1, 1);
addComponent(layout, numbers[2], 1, 1, 1, 1);
addComponent(layout, numbers[3], 1, 2, 1, 1);
addComponent(layout, numbers[4], 2, 0, 1, 1);
addComponent(layout, numbers[5], 2, 1, 1, 1);
addComponent(layout, numbers[6], 2, 2, 1, 1);
addComponent(layout, numbers[7], 3, 0, 1, 1);
addComponent(layout, numbers[8], 3, 1, 1, 1);
addComponent(layout, numbers[9], 3, 2, 1, 1);
addComponent(layout, dot, 4, 0, 1, 1);
addComponent(layout, numbers[0], 4, 1, 1, 1);
addComponent(layout, sqrt, 4, 2, 1, 1);
addComponent(layout, plus, 1, 3, 1, 1);
addComponent(layout, minus, 2, 3, 1, 1);
addComponent(layout, multi, 3, 3, 1, 1);
addComponent(layout, div, 4, 3, 1, 1);
addComponent(layout, equal, 5, 0, 2, 1);
addComponent(layout, changePN, 5, 2, 1, 1);
addComponent(layout, clear, 5, 3, 1, 1);
}
//对按钮进行反应的方法
public void actionPerformed(ActionEvent e)
{
JButton btn=(JButton)e.getSource();
if(btn== clear)
{
operation.setText("0");
dotExist= false;
storedNumber= 0;
lastOperator='?';
}
else if(btn== equal)
{
operate('=');
equaled= true;
}
else if(btn== plus)
{
operate('+');
equaled= false;
}
else if(btn== minus)
{
operate('-');
equaled= false;
}
else if(btn== multi)
{
operate('*');
equaled= false;
}
else if(btn== div)
{
operate('/');
equaled= false;
}
else if(btn== changePN)
{
operate('p');
operate('=');
equaled= true;
}
else if(btn== sqrt)
{
operate('s');
operate('=');
equaled= true;
}
else
{
if(equaled)
storedNumber= 0;
for(int i= 0; i< 10; i++)
if(btn== numbers[i])
{
if(operation.getText().equals("0"))
operation.setText(""+ i);
else if(! operated)
operation.setText(operation.getText()+ i);
else
{
operation.setText(""+ i);
operated= false;
}
}
if(btn== dot&&! dotExist)
{
operation.setText(operation.getText()+".");
dotExist= true;
}
}
}
//进行运算的方法
private void operate(char operator)
{
double currentNumber= Double.valueOf(operation.getText()).doubleValue();
if(lastOperator=='?')
storedNumber= currentNumber;
else if(lastOperator=='+')
storedNumber+= currentNumber;
else if(lastOperator=='-')
storedNumber-= currentNumber;
else if(lastOperator=='*')
storedNumber*= currentNumber;
else if(lastOperator=='/')
storedNumber/= currentNumber;
else if(lastOperator=='p')
storedNumber*=-1;
else if(lastOperator=='s')
storedNumber= Math.sqrt(currentNumber);
else if(lastOperator=='='&& equaled)
storedNumber= currentNumber;
operation.setText(""+ storedNumber);
operated= true;
lastOperator= operator;
}
//快捷使用GridBagLayout的方法
private void addComponent(GridBagLayout layout, Component component, int row, int col, int width, int height)
{
GridBagConstraints constraints= new GridBagConstraints();
constraints.fill= GridBagConstraints.BOTH;
constraints.insets= new Insets(10, 2, 10, 2);
constraints.weightx= 100;
constraints.weighty= 100;
constraints.gridx= col;
constraints.gridy= row;
constraints.gridwidth= width;
constraints.gridheight= height;
layout.setConstraints(component, constraints);
if(component instanceof JButton)
((JButton)component).addActionListener(this);
getContentPane().add(component);
}
//主方法初始化并显示窗口
public static void main(String[] args)
{
Calculator calc= new Calculator();
calc.setSize(290, 400);
calc.setVisible(true);
}
}
如果你想加sin cos tan的话就建它们的按钮在actionPerformed方法中的if-else语句中加else if(btn== sin){operate('S');operate('=');equaled= true;}然后在operate方法加对应的语句就行了.记忆M+, M-没时间搞这个应该比较简单容易明白吧.
java计算器代码
这段代码对你有帮助
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
/**
*我的计算器。MyCalculator继承于 JFrame,是计算器的界面
*/
public class MyCalculator extends JFrame{
private Border border= BorderFactory.createEmptyBorder(5, 5, 5, 5);
private JTextField textbox= new JTextField("0");
private CalculatorCore core= new CalculatorCore();
private ActionListener listener= new ActionListener(){
public void actionPerformed(ActionEvent e){
JButton b=(JButton) e.getSource();
String label= b.getText();
String result= core.process(label);
textbox.setText(result);
}
};
public MyCalculator(String title) throws HeadlessException{
super(title);//调用父类构造方法
setupFrame();//调整窗体属性
setupControls();//创建控件
}
private void setupControls(){
setupDisplayPanel();//创建文本面板
setupButtonsPanel();//创建按钮面板
}
//创建按钮面板并添加按钮
private void setupButtonsPanel(){
JPanel panel= new JPanel();
panel.setBorder(border);
panel.setLayout(new GridLayout(4, 5, 3, 3));
createButtons(panel, new String[]{
"7","8","9","+","C",
"4","5","6","-","CE",
"1","2","3","*","",//空字符串表示这个位置没有按钮
"0",".","=","/",""
});
this.add(panel, BorderLayout.CENTER);
}
/**
*在指定的面板上创建按钮
*
*@param panel要创建按钮的面板
*@param labels按钮文字
*/
private void createButtons(JPanel panel, String[] labels){
for(String label: labels){
//如果 label为空,则表示创建一个空面板。否则创建一个按钮。
if(label.equals("")){
panel.add(new JPanel());
} else{
JButton b= new JButton(label);
b.addActionListener(listener);//为按钮添加侦听器
panel.add(b);
}
}
}
//设置显示面板,用一个文本框来作为计算器的显示部分。
private void setupDisplayPanel(){
JPanel panel= new JPanel();
panel.setLayout(new BorderLayout());
panel.setBorder(border);
setupTextbox();
panel.add(textbox, BorderLayout.CENTER);
this.add(panel, BorderLayout.NORTH);
}
//调整文本框
private void setupTextbox(){
textbox.setHorizontalAlignment(JTextField.RIGHT);//文本右对齐
textbox.setEditable(false);//文本框只读
textbox.setBackground(Color.white);//文本框背景色为白色
}
//调整窗体
private void setupFrame(){
this.setDefaultCloseOperation(EXIT_ON_CLOSE);//当窗体关闭时程序结束
this.setLocation(100, 50);//设置窗体显示在桌面上的位置
this.setSize(300, 200);//设置窗体大小
this.setResizable(false);//窗体大小固定
}
//程序入口
public static void main(String[] args) throws Exception{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
MyCalculator frame= new MyCalculator("我的计算器");
frame.setVisible(true);//在桌面上显示窗体
}
}
/**
*计算器核心逻辑。这个逻辑只能处理 1~2个数的运算。
*/
class CalculatorCore{
private String displayText="0";//要显示的文本
boolean reset= true;
private BigDecimal number1, number2;
private String operator;
private HashMap<String, Operator> operators= new HashMap<String, Operator>();
private HashMap<String, Processor> processors= new HashMap<String, Processor>();
CalculatorCore(){
setupOperators();
setupProcessors();
}
//为每种命令添加处理方式
private void setupProcessors(){
processors.put("[0-9]", new Processor(){
public void calculate(String command){
numberClicked(command);
}
});
processors.put("\\.", new Processor(){
public void calculate(String command){
dotClicked();
}
});
processors.put("=", new Processor(){
public void calculate(String command){
equalsClicked();
}
});
processors.put("[+\\-*/]", new Processor(){
public void calculate(String command){
operatorClicked(command);
}
});
processors.put("C", new Processor(){
public void calculate(String command){
clearClicked();
}
});
processors.put("CE", new Processor(){
public void calculate(String command){
clearErrorClicked();
}
});
}
//为每种 operator添加处理方式
private void setupOperators(){
operators.put("+", new Operator(){
public BigDecimal process(BigDecimal number1, BigDecimal number2){
return number1.add(number2);
}
});
operators.put("-", new Operator(){
public BigDecimal process(BigDecimal number1, BigDecimal number2){
return number1.subtract(number2);
}
});
operators.put("*", new Operator(){
public BigDecimal process(BigDecimal number1, BigDecimal number2){
return number1.multiply(number2);
}
});
operators.put("/", new Operator(){
public BigDecimal process(BigDecimal number1, BigDecimal number2){
return number1.divide(number2, 30, RoundingMode.HALF_UP);
}
});
}
//根据命令处理。这里的命令实际上就是按钮文本。
public String process(String command){
for(String pattern: processors.keySet()){
if(command.matches(pattern)){
processors.get(pattern).calculate(command);
break;
}
}
return displayText;
}
//当按下 CE时
private void clearErrorClicked(){
if(operator== null){
number1= null;
} else{
number2= null;
}
displayText="0";
reset= true;
}
//当按下 C时,将计算器置为初始状态。
private void clearClicked(){
number1= null;
number2= null;
operator= null;
displayText="0";
reset= true;
}
//当按下=时
private void equalsClicked(){
calculateResult();
number1= null;
number2= null;
operator= null;
reset= true;
}
//计算结果
private void calculateResult(){
number2= new BigDecimal(displayText);
Operator oper= operators.get(operator);
if(oper!= null){
BigDecimal result= oper.process(number1, number2);
displayText= result.toString();
}
}
//当按下+-*/时(这里也可以扩展成其他中间操作符)
private void operatorClicked(String command){
if(operator!= null){
calculateResult();
}
number1= new BigDecimal(displayText);
operator= command;
reset= true;
}
//当按下.时
private void dotClicked(){
if(displayText.indexOf(".")==-1){
displayText+=".";
} else if(reset){
displayText="0.";
}
reset= false;
}
//当按下 0-9时
private void numberClicked(String command){
if(reset){
displayText= command;
} else{
displayText+= command;
}
reset= false;
}
//运算符处理接口
interface Operator{
BigDecimal process(BigDecimal number1, BigDecimal number2);
}
//按钮处理接口
interface Processor{
void calculate(String command);
}
}
java 计算器代码
java计算器
import java.awt.*;
import java.awt.event.*;
public class Calculation extends WindowAdapter implements ActionListener
{
double dResult=0;
double dNowInput=0;
double dMemory;
int n=0;//记载小数位数
int nOperation=1;//记录运算符类型
int nBitsNum=0;//记录总共输入的位数
boolean alreadyHaveDot=false;//已经有小数点?
boolean keyAvailable=true;
boolean alreadyClickedEqueal=false;//是否按下过"="?
boolean isTempNowInput=false;//是否在计算出结果后直接按运算符将结果赋给了当前输入值?
Frame f;
Panel p1,p2,p3,p4,p5,p6;
TextField tf1,tf2;
Button b1,b2,b3,b4,b5,b6,b7,b8,b9,b0;
Button bDiv,bSqrt,bMulti,bMinus,bPercent,bPlus,bReciprocal,bEqual,bDot,bNegative;
Button bBackspace,bCE,bC,bMR,bMS,bMC,bM;
java计算器
import java.awt.*;
import java.awt.event.*;
public class Calculation extends WindowAdapter implements ActionListener
{
double dResult=0;
double dNowInput=0;
double dMemory;
int n=0;//记载小数位数
int nOperation=1;//记录运算符类型
int nBitsNum=0;//记录总共输入的位数
boolean alreadyHaveDot=false;//已经有小数点?
boolean keyAvailable=true;
boolean alreadyClickedEqueal=false;//是否按下过"="?
boolean isTempNowInput=false;//是否在计算出结果后直接按运算符将结果赋给了当前输入值?
Frame f;
Panel p1,p2,p3,p4,p5,p6;
TextField tf1,tf2;
Button b1,b2,b3,b4,b5,b6,b7,b8,b9,b0;
Button bDiv,bSqrt,bMulti,bMinus,bPercent,bPlus,bReciprocal,bEqual,bDot,bNegative;
Button bBackspace,bCE,bC,bMR,bMS,bMC,bM;
public void display()
{
f=new Frame("计算器");
f.setSize(280,213);
f.setLocation(200,200);
f.setBackground(Color.LIGHT_GRAY);
f.setResizable(false);
f.setLayout(new BorderLayout(3,3));
p1=new Panel(new GridLayout(1,3,5,5));//用于存放backspace,ce,c三键
p2=new Panel(new GridLayout(4,5,5,5));//用于存放数字区及附近共20键,此处间隙设置可能不合理,以后调整
p3=new Panel(new GridLayout(5,1,5,5));//用于存放MC,MR,MS,M+键及显示M状态文本框,此处间隙设置可能不合理,以后调整
p4=new Panel(new FlowLayout());//用于存放p1,p2
p5=new Panel(new FlowLayout());
p6=new Panel(new FlowLayout());
p4.add(p1);
p4.add(p2);
tf1=new TextField(35);//存放显示区
tf1.setText("0.");
tf1.setEditable(false);
p5.add(tf1);
f.add(p5,BorderLayout.NORTH);
f.add(p4,BorderLayout.CENTER);
f.add(p3,BorderLayout.WEST);
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");
b0=new Button("0");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
b7.addActionListener(this);
b8.addActionListener(this);
b9.addActionListener(this);
b0.addActionListener(this);
bDiv=new Button("/");
bSqrt=new Button("sqrt");
bMulti=new Button("*");
bMinus=new Button("-");
bPercent=new Button("%");
bPlus=new Button("+");
bReciprocal=new Button("1/x");
bEqual=new Button("=");
bDot=new Button(".");
bNegative=new Button("+/-");
bDiv.addActionListener(this);
bSqrt.addActionListener(this);
bMulti.addActionListener(this);
bMinus.addActionListener(this);
bPercent.addActionListener(this);
bPlus.addActionListener(this);
bReciprocal.addActionListener(this);
bEqual.addActionListener(this);
bDot.addActionListener(this);
bNegative.addActionListener(this);
p2.add(b7);
p2.add(b8);
p2.add(b9);
p2.add(bDiv);
p2.add(bSqrt);
p2.add(b4);
p2.add(b5);
p2.add(b6);
p2.add(bMulti);
p2.add(bPercent);
p2.add(b1);
p2.add(b2);
p2.add(b3);
p2.add(bMinus);
p2.add(bReciprocal);
p2.add(b0);
p2.add(bNegative);
p2.add(bDot);
p2.add(bPlus);
p2.add(bEqual);
bBackspace=new Button("Backspace");
bCE=new Button("CE");
bC=new Button("C");
bBackspace.addActionListener(this);
bCE.addActionListener(this);
bC.addActionListener(this);
p1.add(bBackspace);
p1.add(bCE);
p1.add(bC);
tf2=new TextField(2);
tf2.setEnabled(false);
tf2.setBackground(Color.LIGHT_GRAY);
bMC=new Button("MC");
bMR=new Button("MR");
bMS=new Button("MS");
bM=new Button("M+");
bMC.addActionListener(this);
bMR.addActionListener(this);
bMS.addActionListener(this);
bM.addActionListener(this);
p6.add(tf2);
p3.add(p6);
p3.add(bMC);
p3.add(bMR);
p3.add(bMS);
p3.add(bM);
f.setVisible(true);
f.addWindowListener(this);
}
public void actionPerformed(ActionEvent e)
{
//key 0 to 9
if(this.keyAvailable&& e.getActionCommand().length()==1&& e.getActionCommand().compareTo("0")>=0&& e.getActionCommand().compareTo("9")<=0)
{
if(this.isTempNowInput)
{
this.dNowInput=0;
this.isTempNowInput=false;
}
this.nBitsNum++;
if(this.alreadyHaveDot==false)
this.dNowInput=this.dNowInput*10+Double.parseDouble(e.getActionCommand());
else
{
double temp=Double.parseDouble(e.getActionCommand());
for(int i=this.n;i<0;i++)
{
temp*=0.1;
}
this.dNowInput+=temp;
this.n--;
}
this.tf1.setText(Double.toString(this.dNowInput));
}
// key dot
if(this.keyAvailable&& e.getActionCommand()==".")
{
if(this.alreadyHaveDot==false)
{
this.nBitsNum++;
this.alreadyHaveDot=true;
this.n=-1;
}
}
//key"+","-","*","/"
if(this.keyAvailable&& e.getActionCommand()=="+"|| e.getActionCommand()=="-"|| e.getActionCommand()=="*"|| e.getActionCommand()=="/")
{
if(this.alreadyClickedEqueal)
{
this.dNowInput=this.dResult;
this.isTempNowInput=true;
}
else
{
switch(this.nOperation)
{
case 1: this.dResult+=this.dNowInput; break;
case 2: this.dResult-=this.dNowInput; break;
case 3: this.dResult*=this.dNowInput; break;
case 4:
{
if(this.dNowInput==0)
{
tf1.setText("除数不能为零");
this.keyAvailable=false;
}
else this.dResult=this.dResult/this.dNowInput;
}
}
if(this.keyAvailable)tf1.setText(Double.toString(this.dResult));
this.dNowInput=0;
}
if(e.getActionCommand()=="+")
{
this.nOperation=1;
}
if(e.getActionCommand()=="-")
{
this.nOperation=2;
}
if(e.getActionCommand()=="*")
{
this.nOperation=3;
}
if(e.getActionCommand()=="/")
{
this.nOperation=4;
}
this.nBitsNum=0;
this.alreadyClickedEqueal=false;
}
// key"+/-"
if(this.keyAvailable&& e.getActionCommand()=="+/-")
{
this.dNowInput=0-this.dNowInput;
tf1.setText(Double.toString(this.dNowInput));
}
// key"C"
if(e.getActionCommand()=="C")
{
this.nBitsNum=0;
this.dResult=0;
this.dNowInput=0;
this.alreadyHaveDot=false;
this.n=0;
this.nOperation=1;
this.keyAvailable=true;
this.alreadyClickedEqueal=false;
tf1.setText("0.");
}
// key"CE"
if(e.getActionCommand()=="CE")
{
this.nBitsNum=0;
this.dNowInput=0;
this.alreadyHaveDot=false;
this.n=0;
this.nOperation=1;
this.keyAvailable=true;
tf1.setText("0.");
}
// key"sqrt"
if(this.keyAvailable&& e.getActionCommand()=="sqrt")
{
if(this.alreadyClickedEqueal)
{
if(this.dResult>=0)
{
this.dResult=Math.sqrt(this.dResult);
tf1.setText(Double.toString(this.dResult));
}
else
{
tf1.setText("函数输入无效");
this.keyAvailable=false;
}
}
else
{
if(this.dNowInput>=0)
{
this.dNowInput=Math.sqrt(this.dNowInput);
tf1.setText(Double.toString(this.dNowInput));
}
else
{
tf1.setText("函数输入无效");
this.keyAvailable=false;
}
}
}
// key"1/x"
if(this.keyAvailable&& e.getActionCommand()=="1/x")
{
if(this.dNowInput==0)
{
tf1.setText("除数不能为零");
this.keyAvailable=false;
}
else
{
this.dNowInput=1/this.dNowInput;
tf1.setText(Double.toString(this.dNowInput));
}
}
// key"="
if(this.keyAvailable&& e.getActionCommand()=="=")
{
this.alreadyClickedEqueal=true;
switch(this.nOperation)
{
case 1: this.dResult+=this.dNowInput; break;
case 2: this.dResult-=this.dNowInput; break;
case 3: this.dResult*=this.dNowInput; break;
case 4:
{
if(this.dNowInput==0)
{
tf1.setText("除数不能为零");
this.keyAvailable=false;
}
else this.dResult=this.dResult/this.dNowInput;
}
}
if(this.keyAvailable)tf1.setText(Double.toString(this.dResult));
}
// key"MS"
if(this.keyAvailable&& e.getActionCommand()=="MS")
{
this.dMemory=this.dNowInput;
if(this.dMemory!=0)
tf2.setText("M");
}
// key"MC"
if(this.keyAvailable&& e.getActionCommand()=="MC")
{
this.dMemory=0;
tf2.setText("");
}
// key"MR"
if(this.keyAvailable&& e.getActionCommand()=="MR")
{
this.dNowInput=this.dMemory;
tf1.setText(Double.toString(this.dNowInput));
}
// key"M+"
if(this.keyAvailable&& e.getActionCommand()=="M+")
{
this.dMemory+=this.dNowInput;
if(this.dMemory!=0)
tf2.setText("M");
else tf2.setText("");
}
// key"%"
if(this.keyAvailable&& e.getActionCommand()=="%")
{
this.dNowInput=(this.dResult*this.dNowInput)/100;
tf1.setText(Double.toString(this.dNowInput));
}
// key"Backspace"
if(this.keyAvailable&& e.getActionCommand()=="Backspace")
{
if(!this.alreadyClickedEqueal){
if(this.dNowInput!=0)
{
if(this.alreadyHaveDot)
{
if(this.n==-1)
{
this.alreadyHaveDot=false;
this.n=0;
}
else
{
String str,str1;
str=tf1.getText();
str1=str.substring(0,this.nBitsNum-1);
this.nBitsNum--;
this.n++;
this.dNowInput=Double.parseDouble(str1);
tf1.setText(Double.toString(this.dNowInput));
}
}
else
{
int temp;
temp=(int)(this.dNowInput/10);
this.dNowInput=(double)temp;
tf1.setText(Double.toString(this.dNowInput));
}
}
}
}
}
public static void main(String args[])
{
Calculation cal=new Calculation();
cal.display();
}
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
OK,关于java计算器程序代码和java编写简易计算器的内容到此结束了,希望对大家有所帮助。