java科學計算器
Ⅰ 編寫java application程序實現一個簡易計算器
Java計算器源代碼:
importjava.awt.*;
importjava.awt.event.*;
importjavax.swing.*;
/**********************Java計算器主類*********************/
{
JFramef;
JMenumEdit;
JMenumView;
JMenumHelp;
JMenuItemmCopy;
JMenuItemmPaste;
JTextFieldtResult;
JButtonbNumber;
JButtonbOperator;
JButtonbOther;
JButtonbM;
booleanisDouble=false;//是否為實數
intopFlag=-1;
staticdoublet1=0,t2=0,t3=0,result=0;
staticintopflag1=-1,opflag2=-1,flag=0,resflag=1;
intpreOp,currentOp=0;//標准位
doubleop1=0,op2=0;//操作數
doublen3;
StringBufferbuf=newStringBuffer(20);
StringBufferBoard=newStringBuffer(20);//剪貼板
StringBuffermemory=newStringBuffer(20);//M系列
StringBufferstr=newStringBuffer();
//Java計算器構造器
publicSunnyCalculator()
{
f=newJFrame("Sunny計算器_楊梅樹的盔甲");
ContainercontentPane=f.getContentPane();
/**************************Java計算器菜單的創建*****************************/
野升JMenuBarmBar=newJMenuBar();
mBar.setOpaque(true);
mEdit=newJMenu("編輯(E)");
mEdit.setMnemonic(KeyEvent.VK_E);
mCopy=newJMenuItem("復制(C)");
mEdit.add(mCopy);
mPaste=newJMenuItem("粘貼(P)");
mEdit.add(mPaste);
mView=newJMenu("查看(V)");
mView.setMnemonic(KeyEvent.VK_V);
旦仔mView.add(newJMenuItem("標准型"));
mView.add(newJMenuItem("科學型"));
mView.addSeparator();
mView.add(newJMenuItem("查看分組"));
mHelp=newJMenu("幫助(H)");
mHelp.setMnemonic(KeyEvent.VK_H);
mHelp.add(newJMenuItem("幫助主題"));
mHelp.addSeparator();
mHelp.add(newJMenuItem("關於計算器"));
mBar.add(mEdit);
mBar.add(mView);
mBar.add(mHelp);
f.setJMenuBar(mBar);
contentPane.setLayout(newBorderLayout());
JPanelpTop=newJPanel();
tResult=newJTextField("0.",26);
tResult.setHorizontalAlignment(JTextField.RIGHT);
tResult.setEditable(false);
pTop.add(tResult);
contentPane.add(pTop,BorderLayout.NORTH);
JPanelpBottom=new模脊汪JPanel();
pBottom.setLayout(newBorderLayout());
JPanelpLeft=newJPanel();
pLeft.setLayout(newGridLayout(5,1,3,3));
bM=newJButton("");
bM.setEnabled(false);
pLeft.add(bM);
/*************************Java計算器功能鍵定義***************************/
bOther=newJButton("MC");
bOther.addActionListener(this);
bOther.setForeground(Color.red);
bOther.setMargin(newInsets(3,2,3,2));
pLeft.add(bOther);
bOther=newJButton("MR");
bOther.addActionListener(this);
bOther.setForeground(Color.red);
bOther.setMargin(newInsets(3,2,3,2));
pLeft.add(bOther);
bOther=newJButton("MS");
bOther.addActionListener(this);
bOther.setForeground(Color.red);
bOther.setMargin(newInsets(3,2,3,2));
pLeft.add(bOther);
bOther=newJButton("M+");
bOther.addActionListener(this);
bOther.setForeground(Color.red);
bOther.setMargin(newInsets(3,2,3,2));
pLeft.add(bOther);
pBottom.add(pLeft,BorderLayout.WEST);
JPanelpRight=newJPanel();
pRight.setLayout(newBorderLayout());
JPanelpUp=newJPanel();
pUp.setLayout(newGridLayout(1,3,3,0));
bOther=newJButton("BackSpace");
bOther.addActionListener(this);
bOther.setForeground(Color.red);
bOther.setMargin(newInsets(3,0,3,5));
pUp.add(bOther);
bOther=newJButton("CE");
bOther.addActionListener(this);
bOther.setForeground(Color.red);
pUp.add(bOther);
bOther=newJButton("C");
bOther.addActionListener(this);
bOther.setForeground(Color.red);
pUp.add(bOther);
/***************************Java計算器數字鍵盤區定義**************************/
JPanelpDown=newJPanel();
pDown.setLayout(newGridLayout(4,5,3,2));
bNumber=newJButton("7");
bNumber.setForeground(Color.blue);
bNumber.addActionListener(this);
bNumber.setMargin(newInsets(3,3,3,3));
pDown.add(bNumber);
bNumber=newJButton("8");
bNumber.setForeground(Color.blue);
bNumber.addActionListener(this);
bNumber.setMargin(newInsets(3,3,3,3));
pDown.add(bNumber);
bNumber=newJButton("9");
bNumber.setForeground(Color.blue);
bNumber.addActionListener(this);
bNumber.setMargin(newInsets(3,3,3,3));
pDown.add(bNumber);
bOperator=newJButton("/");
bOperator.setForeground(Color.red);
bOperator.addActionListener(this);
bOperator.setMargin(newInsets(3,0,3,0));
pDown.add(bOperator);
bOperator=newJButton("sqrt");
bOperator.addActionListener(this);
bOperator.setForeground(Color.red);
bOperator.setMargin(newInsets(3,0,3,0));
pDown.add(bOperator);
bNumber=newJButton("4");
bNumber.setForeground(Color.blue);
bNumber.addActionListener(this);
bNumber.setMargin(newInsets(3,3,3,3));
bNumber.setHorizontalTextPosition(JButton.LEFT);
pDown.add(bNumber);
bNumber=newJButton("5");
bNumber.setForeground(Color.blue);
bNumber.addActionListener(this);
bNumber.setMargin(newInsets(3,3,3,3));
pDown.add(bNumber);
bNumber=newJButton("6");
bNumber.setForeground(Color.blue);
bNumber.addActionListener(this);
bNumber.setMargin(newInsets(3,3,3,3));
pDown.add(bNumber);
bOperator=newJButton("*");
bOperator.setForeground(Color.red);
bOperator.addActionListener(this);
bOperator.setMargin(newInsets(3,3,3,3));
pDown.add(bOperator);
bOperator=newJButton("%");
bOperator.setForeground(Color.blue);
bOperator.addActionListener(this);
bOperator.setMargin(newInsets(3,3,3,3));
pDown.add(bOperator);
bNumber=newJButton("1");
bNumber.setForeground(Color.blue);
bNumber.addActionListener(this);
bNumber.setMargin(newInsets(3,3,3,3));
pDown.add(bNumber);
bNumber=newJButton("2");
bNumber.setForeground(Color.blue);
bNumber.addActionListener(this);
bNumber.setMargin(newInsets(3,3,3,3));
pDown.add(bNumber);
bNumber=newJButton("3");
bNumber.setForeground(Color.blue);
bNumber.addActionListener(this);
bNumber.setMargin(newInsets(3,3,3,3));
pDown.add(bNumber);
bOperator=newJButton("-");
bOperator.setForeground(Color.red);
bOperator.addActionListener(this);
bOperator.setMargin(newInsets(3,3,3,3));
pDown.add(bOperator);
bOperator=newJButton("1/x");
bOperator.setForeground(Color.blue);
bOperator.addActionListener(this);
pDown.add(bOperator);
bNumber=newJButton("0");
bNumber.setForeground(Color.blue);
bNumber.addActionListener(this);
bNumber.setMargin(newInsets(3,3,3,3));
pDown.add(bNumber);
bOperator=newJButton("+/-");
bOperator.setForeground(Color.blue);
bOperator.addActionListener(this);
bOperator.setMargin(newInsets(3,3,3,3));
pDown.add(bOperator);
bOperator=newJButton(".");
bOperator.setForeground(Color.blue);
bOperator.addActionListener(this);
bOperator.setMargin(newInsets(3,3,3,3));
pDown.add(bOperator);
bOperator=newJButton("+");
bOperator.setForeground(Color.blue);
bOperator.addActionListener(this);
bOperator.setMargin(newInsets(3,3,3,3));
pDown.add(bOperator);
bOperator=newJButton("=");
bOperator.setForeground(Color.blue);
bOperator.addActionListener(this);
bOperator.setMargin(newInsets(3,3,3,3));
pDown.add(bOperator);
pRight.add(pUp,BorderLayout.NORTH);
pRight.add(pDown,BorderLayout.SOUTH);
pBottom.add(pRight,BorderLayout.EAST);
contentPane.add(pBottom,BorderLayout.SOUTH);
f.setSize(newDimension(320,256));
f.setResizable(false);
f.setVisible(true);
f.addWindowListener(newWindowAdapter()
{
publicvoidwindowClosing(WindowEvente)
{
System.exit(0);
}
}
);
}
/************************Java計算器計算方法區***************************/
publicvoidactionPerformed(ActionEvente)
{
Strings=e.getActionCommand();
if(s.equals("復制(C)"))
{
Stringtemp=tResult.getText().trim();
Board.replace(0,Board.length(),temp);
mPaste.setEnabled(true);
}
elseif(s.equals("粘貼(p)"))
{
tResult.setText(Board.toString());
}
elseif(s.equals("CE"))
{
//如果是CE則清除文本框
tResult.setText("0.");
}
elseif(s.equals("BackSpace"))
{
if(!tResult.getText().trim().equals("0."))
{
//如果文本框中有內容
if(str.length()!=1&&str.length()!=0)
{
tResult.setText(str.delete(str.length()-1,str.length()).toString());
}
else
{
tResult.setText("0.");
str.setLength(0);
}
}
op2=Double.parseDouble(tResult.getText().trim());
}
elseif(s.equals("C"))
{
//如果是C刪除當前計算
tResult.setText("0.");
op1=op2=0;
str.replace(0,str.length(),"");
preOp=currentOp=0;
}
elseif(s.equals("MC"))
{
//如果是MC則清除緩沖區
Stringtemp="";
memory.replace(0,memory.length(),temp);
bM.setText("");
}
elseif(s.equals("MR"))
{
//如果按鍵為MR則恢復緩沖區的數到文本框
tResult.setText(memory.toString());
}
elseif(s.equals("MS"))
{
//如果按鍵為MS則將文本框的數存入緩沖區
Strings1=tResult.getText().trim();
memory.replace(0,memory.length(),s1);
bM.setText("M");
}
elseif(s.equals("M+"))
{
//如果按鍵為MS則將文本框值與緩沖區的數相加但不顯示結果
Stringtemp1=tResult.getText().trim();
doubledtemp=Double.parseDouble(temp1);
Stringtemp2=memory.toString();
dtemp+=Double.parseDouble(temp2);
temp1=String.valueOf(dtemp);
memory.replace(0,memory.length(),temp1);
}
elseif(s.equals("1/x"))
{
//如果按鍵為1/x則將文本框中的數據為它的倒數
Stringtemp=tResult.getText().trim();
doubledtemp=Double.parseDouble(temp);
tResult.setText(""+1/dtemp);
}
elseif(s.equals("sqrt"))
{
//如果按鍵為sqrt則將文本框中的內容求平方根
Stringtemp=tResult.getText().trim();
doubledtemp=Double.parseDouble(temp);
tResult.setText(""+Math.sqrt(dtemp));
}
elseif(s.equals("+"))
{
str.setLength(0);
if(currentOp==0)
{
preOp=currentOp=1;
op2=0;
tResult.setText(""+op1);
}
else
{
currentOp=preOp;
preOp=1;
switch(currentOp){
case1:
op1+=op2;
tResult.setText(""+op1);
break;
case2:
op1-=op2;
tResult.setText(""+op1);
break;
case3:
op1*=op2;
tResult.setText(""+op1);
break;
case4:
op1/=op2;
tResult.setText(""+op1);
break;
}
}
}
elseif(s.equals("-")){
str.setLength(0);
if(currentOp==0)
{
preOp=currentOp=2;//op1=op2;op2=0;
tResult.setText(""+op1);
}
else
{
currentOp=preOp;
preOp=2;
switch(currentOp){
case1:op1=op1+op2;tResult.setText(""+op1);break;
case2:op1=op1-op2;tResult.setText(""+op1);break;
case3:op1=op1*op2;tResult.setText(""+op1);break;
case4:op1=op1/op2;tResult.setText(""+op1);break;
}
}
}
elseif(s.equals("*"))//*
{
str.setLength(0);
if(currentOp==0)
{
preOp=currentOp=3;//op1=op2;op2=1;
tResult.setText(""+op1);//op1=op2;
}
else
{
currentOp=preOp;
preOp=3;
switch(currentOp){
case1:op1=op1+op2;tResult.setText(""+op1);break;
case2:op1=op1-op2;tResult.setText(""+op1);break;
case3:op1=op1*op2;tResult.setText(""+op1);break;
case4:op1=op1/op2;tResult.setText(""+op1);break;
}
}
}
elseif(s.equals("/"))///
{
str.setLength(0);
if(currentOp==0)
{
preOp=currentOp=4;//op2=1;
tResult.setText(""+op1);//op1=op2;
}
else
{
currentOp=preOp;
preOp=4;
switch(currentOp){
case1:op1=op1+op2;tResult.setText(""+op1);break;
case2:op1=op1-op2;tResult.setText(""+op1);break;
case3:op1=op1*op2;tResult.setText(""+op1);break;
case4:op1=op1/op2;tResult.setText(""+op1);break;
}
}
}
elseif(s.equals("="))//=
{
if(currentOp==0)
{
str.setLength(0);
tResult.setText(""+op2);
}
else
{
str.setLength(0);
currentOp=preOp;
switch(currentOp){
case1:op1=op1+op2;tResult.setText(""+op1);break;
case2:op1=op1-op2;tResult.setText(""+op1);break;
case3:op1=op1*op2;tResult.setText("&qu
Ⅱ 用JAVA編寫一個計算器
importjava.awt.BorderLayout;
importjava.awt.Color;
importjava.awt.GridLayout;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjavax.swing.ImageIcon;
importjavax.swing.JButton;
importjavax.swing.JFrame;
importjavax.swing.JPanel;
importjavax.swing.JTextField;
importjavax.swing.SwingConstants;
{
/**
*
*/
=1L;
Resultresult=newResult();//定義text的面板
Number_Keynumber_key=newNumber_Key();//定義按鈕面板
//當點擊按鈕+、-、*、/時,com=true
booleancom=false;
//當i=0時說明是我們第一次輸入,字元串text不會累加
inti=0;
//存放text的內容
Stringtext="";
//存放點擊按鈕+、-、*、/之前的數值
doubledefbutton=0;
//+、-、*、/的代號分別為1,2,3,4
intsymbol=0;
//構造函數
Jisuanqi(){
super("WangJiao");//設定標題
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//設定關閉窗體時退出程序
JPanelpane=newJPanel();//定義主面板
pane.setLayout(newBorderLayout());
setBounds(380,220,30,80);//前兩個參數是在屏幕上顯示的坐標,後兩個是大小
//替換圖標
ImageIconicon=newImageIcon("F:1.GIF");
//Jisuanqi.class.getResource("APPLE.GIF")
//);
setIconImage(icon.getImage());
pane.add(result,BorderLayout.NORTH);
pane.add(number_key,BorderLayout.CENTER);
pane.add(number_key.equal,BorderLayout.SOUTH);
number_key.one.addActionListener(this);//對1按鈕添加監聽事件
number_key.two.addActionListener(this);//對2按鈕添加監聽事件
number_key.three.addActionListener(this);//對3按鈕添加監聽事件
number_key.four.addActionListener(this);//對4按鈕添加監聽事件
number_key.five.addActionListener(this);//對5按鈕添加監聽事件
number_key.six.addActionListener(this);//對6按鈕添加監聽事件
number_key.seven.addActionListener(this);//對7按鈕添加監聽事件
number_key.eight.addActionListener(this);//對8按鈕添加監聽事件
number_key.nine.addActionListener(this);//對9按鈕添加監聽事件
number_key.zero.addActionListener(this);//對0按鈕添加監聽事件
number_key.ce.addActionListener(this);//對置零按鈕添加監聽事件
number_key.plus.addActionListener(this);//對+按鈕添加監聽事件
number_key.equal.addActionListener(this);//對=按鈕添加監聽事件
number_key.sub.addActionListener(this);//對-按鈕添加監聽事件
number_key.mul.addActionListener(this);//對*按鈕添加監聽事件
number_key.div.addActionListener(this);//對/按鈕添加監聽事件
number_key.point.addActionListener(this);//對.按鈕添加監聽事件
setContentPane(pane);
pack();//初始化窗體大小為正好盛放所有按鈕
}
//各個按鈕觸發的事件
publicvoidactionPerformed(ActionEvente){
/*
*如果是點擊數字按鈕那麼先要判斷是否在此之前點擊了+、-、*、/、=,如果是那麼com=true如果沒有com=
*false;或者是否點擊數字鍵,如果是i=1,如果沒有i=0;
*/
if(e.getSource()==number_key.one){
if(com||i==0){
result.text.setText("1");
com=false;
i=1;
}else{
text=result.text.getText();
result.text.setText(text+"1");
}
}elseif(e.getSource()==number_key.two){
if(com||i==0){
result.text.setText("2");
com=false;
i=1;
}else{
text=result.text.getText();
result.text.setText(text+"2");
}
}elseif(e.getSource()==number_key.three){
if(com||i==0){
result.text.setText("3");
com=false;
i=1;
}else{
text=result.text.getText();
result.text.setText(text+"3");
}
}elseif(e.getSource()==number_key.four){
if(com||i==0){
result.text.setText("4");
com=false;
i=1;
}else{
text=result.text.getText();
result.text.setText(text+"4");
}
}elseif(e.getSource()==number_key.five){
if(com||i==0){
result.text.setText("5");
com=false;
i=1;
}else{
text=result.text.getText();
result.text.setText(text+"5");
}
}elseif(e.getSource()==number_key.six){
if(com||i==0){
result.text.setText("6");
com=false;
i=1;
}else{
text=result.text.getText();
result.text.setText(text+"6");
}
}elseif(e.getSource()==number_key.seven){
if(com||i==0){
result.text.setText("7");
com=false;
i=1;
}else{
text=result.text.getText();
result.text.setText(text+"7");
}
}elseif(e.getSource()==number_key.eight){
if(com||i==0){
result.text.setText("8");
com=false;
i=1;
}else{
text=result.text.getText();
result.text.setText(text+"8");
}
}elseif(e.getSource()==number_key.nine){
if(com||i==0){
result.text.setText("9");
com=false;
i=1;
}else{
text=result.text.getText();
result.text.setText(text+"9");
}
}
/*
*對於0這個按鈕有一定的說法,在我的程序里不會出現如00000這樣的情況,我加了判斷條件就是
*如果text中的數值=0就要判斷在這個數值中是否有.存在?如果有那麼就在原來數值基礎之上添加0;否則保持原來的數值不變
*/
elseif(e.getSource()==number_key.zero){//result.text.getText()是得到text里內容的意思
if(com||i==0){
result.text.setText("0");
com=false;
i=1;
}else{
text=result.text.getText();
if(Float.parseFloat(text)>0||Float.parseFloat(text)<0){//Float.parseFloat(text)就是類型轉換了,下面都是一樣
result.text.setText(text+"0");
}else{
if(text.trim().indexOf(".")==-1){
result.text.setText(text);
}else{
result.text.setText(text+"0");
}
}
}
}elseif(e.getSource()==number_key.ce){
result.text.setText("0");
i=0;
com=true;
//text="";
defbutton=0;
}
/*
*本程序不會讓一個數值中出現2個以上的小數點.具體做法是:判斷是否已經存在.存在就不添加,不存在就添加.
*/
elseif(e.getSource()==number_key.point){
if(com||i==0){
result.text.setText("0.");
com=false;
i=1;
}else{
text=result.text.getText();
if(text.trim().indexOf(".")==-1){
result.text.setText(text+".");
}else{
result.text.setText(text);
}
}
}//獲得點擊+之前的數值
elseif(e.getSource()==number_key.plus){
com=true;
i=0;
defbutton=Double.parseDouble(result.text.getText());
symbol=1;
}//獲得點擊-之前的數值
elseif(e.getSource()==number_key.sub){
com=true;
i=0;
defbutton=Double.parseDouble(result.text.getText());
symbol=2;
}//獲得點擊*之前的數值
elseif(e.getSource()==number_key.mul){
com=true;
i=0;
defbutton=Double.parseDouble(result.text.getText());
System.out.println(defbutton);
symbol=3;
}//獲得點擊/之前的數值
elseif(e.getSource()==number_key.div){
com=true;
i=0;
defbutton=Double.parseDouble(result.text.getText());
symbol=4;
}elseif(e.getSource()==number_key.equal){
switch(symbol){
case1:{//計算加法
doublead=defbutton
+Double.parseDouble(result.text.getText());
result.text.setText(ad+"");
i=0;
text="";
break;
}
case2:{//計算減法
doublead=defbutton
-Double.parseDouble(result.text.getText());
result.text.setText(String.valueOf(ad));
i=0;
text="";
break;
}
case3:{//計算乘法
doublead=defbutton
*Double.parseDouble(result.text.getText());
result.text.setText(ad+"");
i=0;
text="";
break;
}
case4:{//計算除法
doublead=defbutton
/Double.parseDouble(result.text.getText());
result.text.setText(ad+"");
i=0;
text="";
break;
}
}
System.out.println(com);
}
System.out.println(result.text.getText());
}
@SuppressWarnings("deprecation")
publicstaticvoidmain(String[]args){
Jisuanqiloveyou=newJisuanqi();
loveyou.show();
}
}
//計算器數字按鈕定義面板
classNumber_KeyextendsJPanel{
/**
*
*/
=1L;
JButtonzero=newJButton("0");//數字鍵0
JButtonone=newJButton("1");//數字鍵1
JButtontwo=newJButton("2");//數字鍵2
JButtonthree=newJButton("3");//數字鍵3
JButtonfour=newJButton("4");//數字鍵4
JButtonfive=newJButton("5");//數字鍵5
JButtonsix=newJButton("6");//數字鍵6
JButtonseven=newJButton("7");//數字鍵7
JButtoneight=newJButton("8");//數字鍵8
JButtonnine=newJButton("9");//數字鍵9
JButtonplus=newJButton("+");
JButtonsub=newJButton("-");
JButtonmul=newJButton("*");
JButtondiv=newJButton("/");
JButtonequal=newJButton("=");
JButtonce=newJButton("清零");//置零鍵
JButtonpoint=newJButton(".");
Number_Key(){
setLayout(newGridLayout(4,4,1,1));//定義布局管理器為網格布局
setBackground(Color.blue);//設置背景顏色
//添加按鈕
add(one);
add(two);
add(three);
add(four);
add(five);
add(six);
add(seven);
add(eight);
add(nine);
add(zero);
add(plus);
add(sub);
add(mul);
add(div);
add(point);
add(equal);
add(ce);
}
}
//計算器顯示結果的窗體
classResultextendsJPanel{
/**
*
*/
=1L;
//text先是輸入和結果
JTextFieldtext=newJTextField("0");
@SuppressWarnings("deprecation")
Result(){//講輸入的數字或得到的結果在text的右邊顯示
text.setHorizontalAlignment(SwingConstants.RIGHT);
text.enable(false);//文本框不能編輯
setLayout(newBorderLayout());//設定布局管理器邊框布局
add(text,BorderLayout.CENTER);//text放置在窗體的中間
}
}
直接復制保存成Jisuanqi.java可以直接運行了
Ⅲ java編一個計算器的代碼
界面漂亮堪御尺比系統自帶穗拆兆計算器,功能完美加減乘除開平方等等猜租全部具備,還有清零按鈕,小數點的使用,連加連乘功能完全參考系統官方計算器經過長期調試改進而成,馬上拷貝代碼拿去試試看吧,絕不後悔!
代碼如下:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class Counter {
public static void main(String[] args) {
CounterFrame frame = new CounterFrame();
frame.show();
}
}
class CounterFrame extends JFrame {
public CounterFrame() {
JMenuBar menuBar = new JMenuBar();
JMenu menuFile = new JMenu();
JMenu menuFile1 = new JMenu();
JMenu menuFile2 = new JMenu();
JMenu menuFile3 = new JMenu();
JMenuItem menuFileExit = new JMenuItem();
menuFile.setText("文件");
menuFile1.setText("編輯");
menuFile2.setText("查看");
menuFile3.setText("幫助");
menuFileExit.setText("退出");
menuFileExit.addActionListener
(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
CounterFrame.this.windowClosed();
}
}
);
menuFile.add(menuFileExit);
menuBar.add(menuFile);
menuBar.add(menuFile1);
menuBar.add(menuFile2);
menuBar.add(menuFile3);
setTitle("計算器");
setJMenuBar(menuBar);
setSize(new Dimension(400, 280));
this.getContentPane().add(new Allpanel());
this.addWindowListener
(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
CounterFrame.this.windowClosed();
}
}
);
}
protected void windowClosed() {
System.exit(0);
}
}
class Tool {
public static Tool instance;
private JTextField field;
private Tool() {
this.field=new JTextField(30);
this.field.setHorizontalAlignment(JTextField.RIGHT);
}
public static Tool getinstance()
{
if(instance==null)
{
instance=new Tool();
}
return instance;
}
public JTextField getfield()
{
return (this.field);
}
}
class Allpanel extends JPanel {
public Allpanel() {
this.setLayout(new BorderLayout(0,7));
Northpanel np=new Northpanel();
Centerpanel cp=new Centerpanel();
this.add(np,BorderLayout.NORTH);
this.add(cp,BorderLayout.CENTER);
}
}
class Centercenter extends JPanel {
static Vector Vec=new Vector();
static Vector vc=new Vector();
static Vector vc1=new Vector();
static Vector vc2=new Vector();
static Vector vc3=new Vector();
static String begin="yes";
static double add;
static double jq;
static double cs;
static double cq;
static double dy;
static String jg;
static String what;
static double tool=0;
static String to="yes";
/**
* Method Centercenter
*
*
*/
public Centercenter() {
// TODO: Add your code here
final JTextField text=Tool.getinstance().getfield();
this.setLayout(new GridLayout(4,5,3,3));
String arg[] ={"7","8","9","/","sqrt","4","5","6","*","%","1","2","3","-","1/x","0","+/-",".","+","="};
for(int i=0;i<20;i++)
{
final JButton b=new JButton(arg[i]);
//this.add(new JButton(arg[i]));
this.add(b);
if(i==0||i==1||i==2||i==5||i==6||i==7||i==10||i==11||i==12||i==15)
{
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String mark=b.getText();
String ma=text.getText();
if(vc3.contains("v3"))
{
text.setText("0."+mark);
vc3.clear();
}
else if(vc.contains("a"))
{
if(vc2.contains("v2"))
{
text.setText("0."+mark);
vc.clear();
vc2.clear();
}
else
{
text.setText(mark);
vc.clear();
Vec.clear();
Vec.add(mark);
}
}
else
{
text.setText(ma.trim()+mark);
Vec.add(mark);
}
begin="no";
to="yes";
}
});
}
if(i==17)
{
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String mar=b.getText();
String m=text.getText();
if("yes".equals(begin))
{
vc3.add("v3");
}
if(vc1.contains("v1"))
{
vc2.add("v2");
vc1.clear();
}
if(!Vec.contains(".")&&!vc.contains("a"))
{
text.setText(m.trim()+mar);
Vec.add(".");
}
}
});
}
if(i==18)
{
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String ma=text.getText();
add=Double.parseDouble(ma);
if(what==null)
{
tool=add;
what="add";
}
else
{
tool=tool+add;
text.setText(String.valueOf((tool)));
}
vc.add("a");
vc1.add("v1");
to="+";
}
});
}
if(i==13)
{
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String ma=text.getText();
jq=Double.parseDouble(ma);
if(what==null)
{
tool=jq;
what="jq";
}
else
{
tool=tool-jq;
text.setText(String.valueOf((tool)));
}
vc.add("a");
vc1.add("v1");
to="-";
}
});
}
if(i==3)
{
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String ma=text.getText();
cq=Double.parseDouble(ma);
if(what==null)
{
tool=cq;
what="cq";
}
else
{
tool=tool/cq;
text.setText(String.valueOf((tool)));
}
vc.add("a");
vc1.add("v1");
to="/";
}
});
}
if(i==4)
{
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String ma=text.getText();
cq=Double.parseDouble(ma);
text.setText(String.valueOf(Math.sqrt(cq)));
}
});
}
if(i==8)
{
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String ma=text.getText();
cs=Double.parseDouble(ma);
if(what==null)
{
tool=cs;
what="cs";
}
else
{
tool=tool*cs;
text.setText(String.valueOf((tool)));
}
vc.add("a");
vc1.add("v1");
to="*";
}
});
}
if(i==19)
{
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String ma=text.getText();
dy=Double.parseDouble(ma);
if(what=="add")
{
jg=String.valueOf((tool+dy));
}
if(what=="jq")
{
jg=String.valueOf((tool-dy));
}
if(what=="cs")
{
jg=String.valueOf((tool*dy));
}
if(what=="cq")
{
jg=String.valueOf((tool/dy));
}
if(what==null)
{
if(to=="+")
{
tool=add;
jg=String.valueOf(tool+dy);
}
else if(to=="-")
{
tool=jq;
jg=String.valueOf(dy-tool);
}
else if(to=="*")
{
tool=cs;
jg=String.valueOf(dy*tool);
}
else if(to=="/")
{
tool=cq;
jg=String.valueOf(dy/tool);
}
else
{
jg=String.valueOf(dy);
}
}
text.setText(jg);
Vec.clear();
Vec.add(".");
vc.add("a");
vc1.add("v1");
what=null;
tool=0;
}
});
}
}
}
}
class Centernorth extends JPanel {
public Centernorth() {
final JTextField text=Tool.getinstance().getfield();
JButton jb1=new JButton("Backspace");
JButton jb2=new JButton(" CE ");
JButton jb3=new JButton(" C ");
this.add(jb1);
this.add(jb2);
this.add(jb3);
jb1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String back=Tool.getinstance().getfield().getText();
text.setText(backmethod(back));
Centercenter.Vec.remove(Centercenter.Vec.size()-1);
}
});
jb3.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
text.setText("0.");
Centercenter.Vec.clear();
Centercenter.Vec.add(".");
Centercenter.vc.add("a");
Centercenter.begin="yes";
Centercenter.vc1.clear();
Centercenter.what=null;
Centercenter.tool=0;
}
});
}
public String backmethod(String str)
{
return str.substring(0,str.length()-1);
}
}
class Centerpanel extends JPanel {
public Centerpanel() {
this.setLayout(new BorderLayout(8,7));
Centernorth cn=new Centernorth();
Centercenter cc=new Centercenter();
Centerwest cw=new Centerwest();
this.add(cn,BorderLayout.NORTH);
this.add(cc,BorderLayout.CENTER);
this.add(cw,BorderLayout.WEST);
}
}
class Centerwest extends JPanel {
public Centerwest() {
this.setLayout(new GridLayout(4,1,3,3));
this.add(new JButton("MC"));
this.add(new JButton("MR"));
this.add(new JButton("MS"));
this.add(new JButton("M+"));
}
}
class Northpanel extends JPanel {
private JTextField tf;
public Northpanel() {
tf=Tool.getinstance().getfield();
this.add(tf);
}
}
---------------------------------------------------------------------------
=============《按你要求特意後改過的最簡單功能的代碼如下》========================
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class Counter2 {
public static void main(String[] args) {
CounterFrame frame = new CounterFrame();
frame.show();
}
}
class CounterFrame extends JFrame {
public CounterFrame() {
setTitle("計算器");
setSize(new Dimension(400, 280));
this.getContentPane().add(new Allpanel());
this.addWindowListener
(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
CounterFrame.this.windowClosed();
}
}
);
}
protected void windowClosed() {
System.exit(0);
}
}
class Tool {
public static Tool instance;
private JTextField field;
private Tool() {
this.field=new JTextField(30);
this.field.setHorizontalAlignment(JTextField.RIGHT);
}
public static Tool getinstance()
{
if(instance==null)
{
instance=new Tool();
}
return instance;
}
public JTextField getfield()
{
return (this.field);
}
}
class Allpanel extends JPanel {
public Allpanel() {
this.setLayout(new BorderLayout(0,7));
Northpanel np=new Northpanel();
Centerpanel cp=new Centerpanel();
this.add(np,BorderLayout.NORTH);
this.add(cp,BorderLayout.CENTER);
}
}
class Centercenter extends JPanel {
static Vector Vec=new Vector();
static Vector vc=new Vector();
static Vector vc1=new Vector();
static Vector vc2=new Vector();
static Vector vc3=new Vector();
static String begin="yes";
static double add;
static double jq;
static double cs;
static double cq;
static double dy;
static String jg;
static String what;
static double tool=0;
static String to="yes";
/**
* Method Centercenter
*
*
*/
public Centercenter() {
// TODO: Add your code here
final JTextField text=Tool.getinstance().getfield();
this.setLayout(new GridLayout(4,5,3,3));
String arg[] ={"7","8","9","/","4","5","6","*","1","2","3","-","0","=",".","+"};
for(int i=0;i<16;i++)
{
final JButton b=new JButton(arg[i]);
//this.add(new JButton(arg[i]));
this.add(b);
if(i==0||i==1||i==2||i==4||i==5||i==6||i==8||i==9||i==10||i==12)
{
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String mark=b.getText();
String ma=text.getText();
if(vc3.contains("v3"))
{
text.setText("0."+mark);
vc3.clear();
}
else if(vc.contains("a"))
{
if(vc2.contains("v2"))
{
text.setText("0."+mark);
vc.clear();
vc2.clear();
}
else
{
text.setText(mark);
vc.clear();
Vec.clear();
Vec.add(mark);
}
}
else
{
text.setText(ma.trim()+mark);
Vec.add(mark);
}
begin="no";
to="yes";
}
});
}
if(i==14)
{
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String mar=b.getText();
String m=text.getText();
if("yes".equals(begin))
{
vc3.add("v3");
}
if(vc1.contains("v1"))
{
vc2.add("v2");
vc1.clear();
}
if(!Vec.contains(".")&&!vc.contains("a"))
{
text.setText(m.trim()+mar);
Vec.add(".");
}
}
});
}
if(i==15)
{
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String ma=text.getText();
add=Double.parseDouble(ma);
if(what==null)
{
tool=add;
what="add";
}
else
{
tool=tool+add;
text.setText(String.valueOf((tool)));
}
vc.add("a");
vc1.add("v1");
to="+";
}
});
}
if(i==11)
{
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String ma=text.getText();
jq=Double.parseDouble(ma);
if(what==null)
{
tool=jq;
what="jq";
}
else
{
tool=tool-jq;
text.setText(String.valueOf((tool)));
}
vc.add("a");
vc1.add("v1");
to="-";
}
});
}
if(i==3)
{
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String ma=text.getText();
cq=Double.parseDouble(ma);
if(what==null)
{
tool=cq;
what="cq";
}
else
{
tool=tool/cq;
text.setText(String.valueOf((tool)));
}
vc.add("a");
vc1.add("v1");
to="/";
}
});
}
if(i==7)
{
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String ma=text.getText();
cs=Double.parseDouble(ma);
if(what==null)
{
tool=cs;
what="cs";
}
else
{
tool=tool*cs;
text.setText(String.valueOf((tool)));
}
vc.add("a");
vc1.add("v1");
to="*";
}
});
}
if(i==13)
{
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String ma=text.getText();
dy=Double.parseDouble(ma);
if(what=="add")
{
jg=String.valueOf((tool+dy));
}
if(what=="jq")
{
jg=String.valueOf((tool-dy));
}
if(what=="cs")
{
jg=String.valueOf((tool*dy));
}
if(what=="cq")
{
jg=String.valueOf((tool/dy));
}
if(what==null)
{
if(to=="+")
{
tool=add;
jg=String.valueOf(tool+dy);
}
else if(to=="-")
{
tool=jq;
jg=String.valueOf(dy-tool);
}
else if(to=="*")
{
tool=cs;
jg=String.valueOf(dy*tool);
}
else if(to=="/")
{
tool=cq;
jg=String.valueOf(dy/tool);
}
else
{
jg=String.valueOf(dy);
}
}
text.setText(jg);
Vec.clear();
Vec.add(".");
vc.add("a");
vc1.add("v1");
what=null;
tool=0;
}
});
}
}
}
}
class Centernorth extends JPanel {
public Centernorth() {
final JTextField text=Tool.getinstance().getfield();
}
}
class Centerpanel extends JPanel {
public Centerpanel() {
this.setLayout(new BorderLayout(8,7));
Centernorth cn=new Centernorth();
Centercenter cc=new Centercenter();
Centerwest cw=new Centerwest();
this.add(cn,BorderLayout.NORTH);
this.add(cc,BorderLayout.CENTER);
this.add(cw,BorderLayout.WEST);
}
}
class Centerwest extends JPanel {
public Centerwest() {
}
}
class Northpanel extends JPanel {
private JTextField tf;
public Northpanel() {
tf=Tool.getinstance().getfield();
this.add(tf);
}
}
------------------------------------------------------------
才子_輝祝您愉快!
Ⅳ 用java.EE編寫計算器程序代碼
java EE是java企業級開發平台的意思,實在是看不出跟計算器這種小程序有什麼關聯。不知道樓主要找棚芹旦的是不是這個。
package ex1;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JTextField;
public class Calcutor extends JFrame {
private JTextField tf;
private JPanel panel1, panel2, panel3, panel4;
private JMenuBar myBar;
private JMenu menu1, menu2, menu3;
private JMenuItem editItem1, editItem2, help1, help2, help3;
private JRadioButtonMenuItem seeItem1, seeItem2;//單選框
private JCheckBoxMenuItem seeItem3;//復選框
private ButtonGroup bgb;
private String back;
private boolean IfResult = true, flag = false;
private String oper = "鏈擾=";
private double result = 0;
private Num numActionListener;
private DecimalFormat df;
public Calcutor(){
super("科首此學計算器");//設置標題欄
df = new DecimalFormat("#.####");//保留四位小數
this.setLayout(new BorderLayout(10, 5));
panel1 = new JPanel(new GridLayout(1, 3, 10, 10));
panel2 = new JPanel(new GridLayout(5, 6, 5, 5));//5行6列
panel3 = new JPanel(new GridLayout(5, 1, 5, 5));
panel4 = new JPanel(new BorderLayout(5, 5));
/**
* 菜單欄
*/
myBar = new JMenuBar();
menu1 = new JMenu("編輯(E)");
menu2 = new JMenu("查看(V)");
menu3 = new JMenu("幫助(H)");
menu1.setFont(new Font("宋體", Font.PLAIN, 12));
menu2.setFont(new Font("宋體", Font.PLAIN, 12));
menu3.setFont(new Font("宋體", Font.PLAIN, 12));
/**
* 編輯欄
*/
editItem1 = new JMenuItem("復制(C) Ctrl+C");
editItem2 = new JMenuItem("粘貼(P) Ctrl+V");
editItem1.setFont(new Font("宋體",Font.PLAIN,12));
editItem2.setFont(new Font("宋體",Font.PLAIN,12));
/**
* 查看欄
*/
seeItem1 = new JRadioButtonMenuItem("科學型(T)");
seeItem2 = new JRadioButtonMenuItem("標准型(S)");
seeItem3 = new JCheckBoxMenuItem("數字分組(I)");
seeItem1.setFont(new Font("宋體",Font.PLAIN,12));
seeItem2.setFont(new Font("宋體",Font.PLAIN,12));
seeItem3.setFont(new Font("宋體",Font.PLAIN,12));
/**
* 幫助欄
*/
help1 = new JMenuItem("幫助主題(H)");
help2 = new JMenuItem("關於計算器(A)");
help1.setFont(new Font("宋體",Font.PLAIN,12));
help2.setFont(new Font("宋體",Font.PLAIN,12));
bgb = new ButtonGroup();//選項組
menu1.add(editItem1);
menu1.add(editItem2);
menu2.add(seeItem1);
menu2.add(seeItem2);
menu2.addSeparator();//添加一條分割線
menu2.add(seeItem3);
menu3.add(help1);
menu3.addSeparator();//添加一條分割線
menu3.add(help2);
myBar.add(menu1);
myBar.add(menu2);
myBar.add(menu3);
this.setJMenuBar(myBar);
numActionListener = new Num();//實現數字監聽
/**
* 文本域,即為計算器的屏幕顯示區域
*/
tf = new JTextField();
tf.setEditable(false);//文本區域不可編輯
tf.setBackground(Color.white);//文本區域的背景色
tf.setHorizontalAlignment(JTextField.RIGHT);//文字右對齊
tf.setText("0");
tf.setBorder(BorderFactory.createLoweredBevelBorder());
init();//對計算器進行初始化
}
/**
* 初始化操作
* 添加按鈕
*/
private void init(){
addButton(panel1, "Backspace", new Clear(), Color.red);
addButton(panel1, "CE", new Clear(), Color.red);
addButton(panel1, "C", new Clear(), Color.red);
addButton(panel2, "1/x", new Signs(), Color.magenta);
addButton(panel2, "log", new Signs(), Color.magenta);
addButton(panel2, "7", numActionListener, Color.blue);
addButton(panel2, "8", numActionListener, Color.blue);
addButton(panel2, "9", numActionListener, Color.blue);
addButton(panel2, "÷", new Signs(), Color.red);
addButton(panel2, "n!", new Signs(), Color.magenta);
addButton(panel2, "sqrt", new Signs(), Color.magenta);
addButton(panel2, "4", numActionListener, Color.blue);
addButton(panel2, "5", numActionListener, Color.blue);
addButton(panel2, "6", numActionListener, Color.blue);
addButton(panel2, "×", new Signs(), Color.red);
addButton(panel2, "sin", new Signs(), Color.magenta);
addButton(panel2, "x^2", new Signs(), Color.magenta);
addButton(panel2, "1", numActionListener, Color.blue);
addButton(panel2, "2", numActionListener, Color.blue);
addButton(panel2, "3", numActionListener, Color.blue);
addButton(panel2, "-", new Signs(), Color.red);
addButton(panel2, "cos", new Signs(), Color.magenta);
addButton(panel2, "x^3", new Signs(), Color.magenta);
addButton(panel2, "0", numActionListener, Color.blue);
addButton(panel2, "-/+", new Clear(), Color.blue);
addButton(panel2, ".", new Dot(), Color.blue);
addButton(panel2, "+", new Signs(), Color.red);
addButton(panel2, "tan", new Signs(), Color.magenta);
addButton(panel2, "%", new Signs(), Color.magenta);
addButton(panel2, "π", numActionListener, Color.orange);
addButton(panel2, "e", numActionListener, Color.orange);
addButton(panel2, "′″", new Signs(), Color.orange);
addButton(panel2, "=", new Signs(), Color.red);
JButton btns = new JButton("計算器");
btns.setBorder(BorderFactory.createLoweredBevelBorder());
btns.setEnabled(false);//按鈕不可操作
btns.setPreferredSize(new Dimension(20, 20));
panel3.add(btns);//加入按鈕
addButton(panel3, "MC", null, Color.red);
addButton(panel3, "MR", null, Color.red);
addButton(panel3, "MS", null, Color.red);
addButton(panel3, "M+", null, Color.red);
panel4.add(panel1, BorderLayout.NORTH);
panel4.add(panel2, BorderLayout.CENTER);
this.add(tf, BorderLayout.NORTH);
this.add(panel3, BorderLayout.WEST);
this.add(panel4);
pack();
this.setResizable(false);//窗口不可改變大小
this.setLocation(300, 200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
/**
* 統一設置按鈕的的使用方式
* @param panel
* @param name
* @param action
* @param color
*/
private void addButton(JPanel panel, String name, ActionListener action, Color color){
JButton bt = new JButton(name);
panel.add(bt);//在面板上增加按鈕
bt.setForeground(color);//設置前景(字體)顏色
bt.addActionListener(action);//增加監聽事件
}
/**
* 計算器的基礎操作(+ - × ÷)
* @param x
*/
private void getResult (double x){
if(oper == "+"){result += x;}
else if(oper == "-"){result -= x;}
else if(oper == "×"){result *= x;}
else if(oper == "÷"){result /= x;}
else if(oper == "="){result = x;}
tf.setText(df.format(result));
}
/**
* 運算符號的事件監聽
*/
class Signs implements ActionListener{
public void actionPerformed(ActionEvent e) {
/*
* 用ActionEvent對象的getActionCommand()方法
* 取得與引發事件對象相關的字元串
*/
String str = e.getActionCommand();
/* sqrt求平方根 */
if(str.equals("sqrt")){
double i = Double.parseDouble(tf.getText());
if(i>=0){
/*
* String.valueOf() 轉換為字元串
* df.format() 按要求保留四位小數
* Math.sqrt() 求算數平方根
*/
tf.setText(String.valueOf(df.format(Math.sqrt(i))));
}
else{
tf.setText("負數不能開平方根");
}
}
/* log求常用對數 */
else if(str.equals("log")){
double i = Double.parseDouble(tf.getText());
if(i>0){
tf.setText(String.valueOf(df.format(Math.log(i))));
}else{
tf.setText("負數不能求對數");
}
}
/* %求百分比 */
else if(str.equals("%")){
tf.setText(df.format(Double.parseDouble(tf.getText()) / 100));
}
/* 1/x求倒數 */
else if(str.equals("1/x")){
if(Double.parseDouble(tf.getText()) == 0){
tf.setText("除數不能為零");
}else{
tf.setText(df.format(1 / Double.parseDouble(tf.getText())));
}
}
/* sin求正弦函數 */
else if(str.equals("sin")){
double i = Double.parseDouble(tf.getText());
tf.setText(String.valueOf(df.format(Math.sin(i))));
}
/* cos求餘弦函數 */
else if(str.equals("cos")){
double i = Double.parseDouble(tf.getText());
tf.setText(String.valueOf(df.format(Math.cos(i))));
}
/* tan求正切函數 */
else if(str.equals("tan")){
double i = Double.parseDouble(tf.getText());
tf.setText(String.valueOf(df.format(Math.tan(i))));
}
/* n!求階乘 */
else if(str.equals("n!")){
double i = Double.parseDouble(tf.getText());
if((i%2==0)||(i%2==1))//判斷為整數放進行階乘操作
{
int j = (int)i;//強制類型轉換
int result=1;
for(int k=1;k<=j;k++)
result *= k;
tf.setText(String.valueOf(result));
}
else
{
tf.setText("無法進行階乘");
}
}
/* x^2求平方 */
else if(str.equals("x^2")){
double i = Double.parseDouble(tf.getText());
tf.setText(String.valueOf(df.format(i*i)));
}
/* x^3求立方 */
else if(str.equals("x^3")){
double i = Double.parseDouble(tf.getText());
tf.setText(String.valueOf(df.format(i*i*i)));
}
/* ′″角度轉換 */
/**
* 將角度值轉換成弧度值,方便三角函數的計算
*/
else if(str.equals("′″")){
double i = Double.parseDouble(tf.getText());
tf.setText(String.valueOf(i/180*Math.PI));
}
else{
if(flag){
IfResult = false;
}
if(IfResult){
oper = str;
}else{
getResult(Double.parseDouble(tf.getText()));
oper = str;
IfResult = true;
}
}
}
}
/**
* 清除按鈕的事件監聽
*/
class Clear implements ActionListener{
public void actionPerformed(ActionEvent e) {
/*
* 用ActionEvent對象的getActionCommand()方法
* 取得與引發事件對象相關的字元串
*/
String str = e.getActionCommand();
if(str == "C"){
tf.setText("0");
IfResult = true;
result = 0;
}else if(str == "-/+"){
double i = 0 - Double.parseDouble(tf.getText().trim());
tf.setText(df.format(i));
}else if(str == "Backspace"){
if(Double.parseDouble(tf.getText()) > 0){
if(tf.getText().length() > 1){
tf.setText(tf.getText().substring(0, tf.getText().length() - 1));
//使用退格刪除最後一位字元
}else{
tf.setText("0");
IfResult = true;
}
}else{
if(tf.getText().length() > 2){
tf.setText(tf.getText().substring(0, tf.getText().length() - 1));
}else{
tf.setText("0");
IfResult = true;
}
}
}else if(str == "CE"){
tf.setText("0");
IfResult = true;
}
}
}
/**
* 數字輸入的事件監聽
*/
class Num implements ActionListener{
public void actionPerformed(ActionEvent e) {
String str = e.getActionCommand();
if(IfResult){
tf.setText("");
IfResult = false;
}
if(str=="π")
{
tf.setText(String.valueOf(Math.PI));
}
else if(str=="e")
{
tf.setText(String.valueOf(Math.E));
}
else{
tf.setText(tf.getText().trim() + str);
if(tf.getText().equals("0")){
tf.setText("0");
IfResult = true;
flag = true;
}
}
}
}
/**
* 小數點的事件監聽
*/
class Dot implements ActionListener{
public void actionPerformed(ActionEvent e) {
IfResult = false;
if(tf.getText().trim().indexOf(".") == -1){
tf.setText(tf.getText() + ".");
}
}
}
/**
* main方法
*/
public static void main(String[] args) {
new Calcutor().setVisible(true);
}
}
Ⅳ Java計算器源代碼
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;public class CaculatorA {
private JFrame jf;
private JButton[] jbs;
private JTextField jtf;
private JButton clear;
private double num1,num2,jieguo;
private char c;
/**
* 構造方顫答法實例化屬性
*
*/
public CaculatorA(){
jf=new JFrame("我的明缺計算器v1.0");
jtf=new JTextField(20);
clear=new JButton("clear");
jbs=new JButton[16];
String str="123+456-789*0./=";
for(int i=0; i<茄槐慧str.length(); i++){
jbs[i]=new JButton(str.charAt(i)+"");
}
init();
addEventHandler();
// setFont();
// setColor();
showMe();
}
/**
Ⅵ java中,用布局器實現計算器界面 並實現加減乘除等功能,怎樣編程
java寫的,可行
package ex1;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JTextField;
public class Calcutor extends JFrame {
private JTextField tf;
private JPanel panel1, panel2, panel3, panel4;
private JMenuBar myBar;
private JMenu menu1, menu2, menu3;
private JMenuItem editItem1, editItem2, help1, help2, help3;
private JRadioButtonMenuItem seeItem1, seeItem2;//單選框
private JCheckBoxMenuItem seeItem3;//復選框
private ButtonGroup bgb;
private String back;
private boolean IfResult = true, flag = false;
private String oper = "=";
private double result = 0;
private Num numActionListener;
private DecimalFormat df;
public Calcutor(){
super("科學計拿告猛算器");//設置標題欄
df = new DecimalFormat("#.####");//保留四位小數
this.setLayout(new BorderLayout(10, 5));
panel1 = new JPanel(new GridLayout(1, 3, 10, 10));
panel2 = new JPanel(new GridLayout(5, 6, 5, 5));//5行6列
panel3 = new JPanel(new GridLayout(5, 1, 5, 5));
panel4 = new JPanel(new BorderLayout(5, 5));
/**
* 菜單欄
*/
myBar = new JMenuBar();
menu1 = new JMenu("編輯(E)");
menu2 = new JMenu("查看(V)");
menu3 = new JMenu("幫助(H)");
menu1.setFont(new Font("宋體", Font.PLAIN, 12));
menu2.setFont(new Font("宋體", Font.PLAIN, 12));
menu3.setFont(new Font("宋體友大", Font.PLAIN, 12));
/**
* 編輯欄
*/
editItem1 = new JMenuItem("復制(C) Ctrl+C");
editItem2 = new JMenuItem("粘消橋貼(P) Ctrl+V");
editItem1.setFont(new Font("宋體",Font.PLAIN,12));
editItem2.setFont(new Font("宋體",Font.PLAIN,12));
/**
* 查看欄
*/
seeItem1 = new JRadioButtonMenuItem("科學型(T)");
seeItem2 = new JRadioButtonMenuItem("標准型(S)");
seeItem3 = new JCheckBoxMenuItem("數字分組(I)");
seeItem1.setFont(new Font("宋體",Font.PLAIN,12));
seeItem2.setFont(new Font("宋體",Font.PLAIN,12));
seeItem3.setFont(new Font("宋體",Font.PLAIN,12));
/**
* 幫助欄
*/
help1 = new JMenuItem("幫助主題(H)");
help2 = new JMenuItem("關於計算器(A)");
help1.setFont(new Font("宋體",Font.PLAIN,12));
help2.setFont(new Font("宋體",Font.PLAIN,12));
bgb = new ButtonGroup();//選項組
menu1.add(editItem1);
menu1.add(editItem2);
menu2.add(seeItem1);
menu2.add(seeItem2);
menu2.addSeparator();//添加一條分割線
menu2.add(seeItem3);
menu3.add(help1);
menu3.addSeparator();//添加一條分割線
menu3.add(help2);
myBar.add(menu1);
myBar.add(menu2);
myBar.add(menu3);
this.setJMenuBar(myBar);
numActionListener = new Num();//實現數字監聽
/**
* 文本域,即為計算器的屏幕顯示區域
*/
tf = new JTextField();
tf.setEditable(false);//文本區域不可編輯
tf.setBackground(Color.white);//文本區域的背景色
tf.setHorizontalAlignment(JTextField.RIGHT);//文字右對齊
tf.setText("0");
tf.setBorder(BorderFactory.createLoweredBevelBorder());
init();//對計算器進行初始化
}
/**
* 初始化操作
* 添加按鈕
*/
private void init(){
addButton(panel1, "Backspace", new Clear(), Color.red);
addButton(panel1, "CE", new Clear(), Color.red);
addButton(panel1, "C", new Clear(), Color.red);
addButton(panel2, "1/x", new Signs(), Color.magenta);
addButton(panel2, "log", new Signs(), Color.magenta);
addButton(panel2, "7", numActionListener, Color.blue);
addButton(panel2, "8", numActionListener, Color.blue);
addButton(panel2, "9", numActionListener, Color.blue);
addButton(panel2, "÷", new Signs(), Color.red);
addButton(panel2, "n!", new Signs(), Color.magenta);
addButton(panel2, "sqrt", new Signs(), Color.magenta);
addButton(panel2, "4", numActionListener, Color.blue);
addButton(panel2, "5", numActionListener, Color.blue);
addButton(panel2, "6", numActionListener, Color.blue);
addButton(panel2, "×", new Signs(), Color.red);
addButton(panel2, "sin", new Signs(), Color.magenta);
addButton(panel2, "x^2", new Signs(), Color.magenta);
addButton(panel2, "1", numActionListener, Color.blue);
addButton(panel2, "2", numActionListener, Color.blue);
addButton(panel2, "3", numActionListener, Color.blue);
addButton(panel2, "-", new Signs(), Color.red);
addButton(panel2, "cos", new Signs(), Color.magenta);
addButton(panel2, "x^3", new Signs(), Color.magenta);
addButton(panel2, "0", numActionListener, Color.blue);
addButton(panel2, "-/+", new Clear(), Color.blue);
addButton(panel2, ".", new Dot(), Color.blue);
addButton(panel2, "+", new Signs(), Color.red);
addButton(panel2, "tan", new Signs(), Color.magenta);
addButton(panel2, "%", new Signs(), Color.magenta);
addButton(panel2, "π", numActionListener, Color.orange);
addButton(panel2, "e", numActionListener, Color.orange);
addButton(panel2, "′″", new Signs(), Color.orange);
addButton(panel2, "=", new Signs(), Color.red);
JButton btns = new JButton("計算器");
btns.setBorder(BorderFactory.createLoweredBevelBorder());
btns.setEnabled(false);//按鈕不可操作
btns.setPreferredSize(new Dimension(20, 20));
panel3.add(btns);//加入按鈕
addButton(panel3, "MC", null, Color.red);
addButton(panel3, "MR", null, Color.red);
addButton(panel3, "MS", null, Color.red);
addButton(panel3, "M+", null, Color.red);
panel4.add(panel1, BorderLayout.NORTH);
panel4.add(panel2, BorderLayout.CENTER);
this.add(tf, BorderLayout.NORTH);
this.add(panel3, BorderLayout.WEST);
this.add(panel4);
pack();
this.setResizable(false);//窗口不可改變大小
this.setLocation(300, 200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
/**
* 統一設置按鈕的的使用方式
* @param panel
* @param name
* @param action
* @param color
*/
private void addButton(JPanel panel, String name, ActionListener action, Color color){
JButton bt = new JButton(name);
panel.add(bt);//在面板上增加按鈕
bt.setForeground(color);//設置前景(字體)顏色
bt.addActionListener(action);//增加監聽事件
}
/**
* 計算器的基礎操作(+ - × ÷)
* @param x
*/
private void getResult (double x){
if(oper == "+"){result += x;}
else if(oper == "-"){result -= x;}
else if(oper == "×"){result *= x;}
else if(oper == "÷"){result /= x;}
else if(oper == "="){result = x;}
tf.setText(df.format(result));
}
/**
* 運算符號的事件監聽
*/
class Signs implements ActionListener{
public void actionPerformed(ActionEvent e) {
/*
* 用ActionEvent對象的getActionCommand()方法
* 取得與引發事件對象相關的字元串
*/
String str = e.getActionCommand();
/* sqrt求平方根 */
if(str.equals("sqrt")){
double i = Double.parseDouble(tf.getText());
if(i>=0){
/*
* String.valueOf() 轉換為字元串
* df.format() 按要求保留四位小數
* Math.sqrt() 求算數平方根
*/
tf.setText(String.valueOf(df.format(Math.sqrt(i))));
}
else{
tf.setText("負數不能開平方根");
}
}
/* log求常用對數 */
else if(str.equals("log")){
double i = Double.parseDouble(tf.getText());
if(i>0){
tf.setText(String.valueOf(df.format(Math.log(i))));
}else{
tf.setText("負數不能求對數");
}
}
/* %求百分比 */
else if(str.equals("%")){
tf.setText(df.format(Double.parseDouble(tf.getText()) / 100));
}
/* 1/x求倒數 */
else if(str.equals("1/x")){
if(Double.parseDouble(tf.getText()) == 0){
tf.setText("除數不能為零");
}else{
tf.setText(df.format(1 / Double.parseDouble(tf.getText())));
}
}
/* sin求正弦函數 */
else if(str.equals("sin")){
double i = Double.parseDouble(tf.getText());
tf.setText(String.valueOf(df.format(Math.sin(i))));
}
/* cos求餘弦函數 */
else if(str.equals("cos")){
double i = Double.parseDouble(tf.getText());
tf.setText(String.valueOf(df.format(Math.cos(i))));
}
/* tan求正切函數 */
else if(str.equals("tan")){
double i = Double.parseDouble(tf.getText());
tf.setText(String.valueOf(df.format(Math.tan(i))));
}
/* n!求階乘 */
else if(str.equals("n!")){
double i = Double.parseDouble(tf.getText());
if((i%2==0)||(i%2==1))//判斷為整數放進行階乘操作
{
int j = (int)i;//強制類型轉換
int result=1;
for(int k=1;k<=j;k++)
result *= k;
tf.setText(String.valueOf(result));
}
else
{
tf.setText("無法進行階乘");
}
}
/* x^2求平方 */
else if(str.equals("x^2")){
double i = Double.parseDouble(tf.getText());
tf.setText(String.valueOf(df.format(i*i)));
}
/* x^3求立方 */
else if(str.equals("x^3")){
double i = Double.parseDouble(tf.getText());
tf.setText(String.valueOf(df.format(i*i*i)));
}
/* ′″角度轉換 */
/**
* 將角度值轉換成弧度值,方便三角函數的計算
*/
else if(str.equals("′″")){
double i = Double.parseDouble(tf.getText());
tf.setText(String.valueOf(i/180*Math.PI));
}
else{
if(flag){
IfResult = false;
}
if(IfResult){
oper = str;
}else{
getResult(Double.parseDouble(tf.getText()));
oper = str;
IfResult = true;
}
}
}
}
/**
* 清除按鈕的事件監聽
*/
class Clear implements ActionListener{
public void actionPerformed(ActionEvent e) {
/*
* 用ActionEvent對象的getActionCommand()方法
* 取得與引發事件對象相關的字元串
*/
String str = e.getActionCommand();
if(str == "C"){
tf.setText("0");
IfResult = true;
result = 0;
}else if(str == "-/+"){
double i = 0 - Double.parseDouble(tf.getText().trim());
tf.setText(df.format(i));
}else if(str == "Backspace"){
if(Double.parseDouble(tf.getText()) > 0){
if(tf.getText().length() > 1){
tf.setText(tf.getText().substring(0, tf.getText().length() - 1));
//使用退格刪除最後一位字元
}else{
tf.setText("0");
IfResult = true;
}
}else{
if(tf.getText().length() > 2){
tf.setText(tf.getText().substring(0, tf.getText().length() - 1));
}else{
tf.setText("0");
IfResult = true;
}
}
}else if(str == "CE"){
tf.setText("0");
IfResult = true;
}
}
}
/**
* 數字輸入的事件監聽
*/
class Num implements ActionListener{
public void actionPerformed(ActionEvent e) {
String str = e.getActionCommand();
if(IfResult){
tf.setText("");
IfResult = false;
}
if(str=="π")
{
tf.setText(String.valueOf(Math.PI));
}
else if(str=="e")
{
tf.setText(String.valueOf(Math.E));
}
else{
tf.setText(tf.getText().trim() + str);
if(tf.getText().equals("0")){
tf.setText("0");
IfResult = true;
flag = true;
}
}
}
}
/**
* 小數點的事件監聽
*/
class Dot implements ActionListener{
public void actionPerformed(ActionEvent e) {
IfResult = false;
if(tf.getText().trim().indexOf(".") == -1){
tf.setText(tf.getText() + ".");
}
}
}
/**
* main方法
*/
public static void main(String[] args) {
new Calcutor().setVisible(true);
}
}
Ⅶ JAVA製作一個簡單的計算器。能實現兩個數的加、減、乘、除四則運算
import搜芹大java.util.*;
importjava.awt.*;
import首升java.awt.event.*;
importjavax.swing.*;
importjava.applet.*;
{
booleani=true;
privateJButtonnum0=newJButton("0");
privateJButtonnum1=newJButton("1");
privateJButtonnum2=newJButton("2");
privateJButtonnum3=newJButton("3");
privateJButtonnum4=newJButton("4");
privateJButtonnum5=newJButton("5");
privateJButtonnum6=newJButton("6");
privateJButtonnum7=newJButton("7");
privateJButtonnum8=newJButton("8");
privateJButtonnum9=newJButton("9");
privateJButtonzuok=newJButton("(");
privateJButtonyouk=newJButton(")");
privateJButtondian=newJButton(".");
privateJButtonNULL=newJButton("世豎N");
privateJButtonplu=newJButton("+");
privateJButtonmin=newJButton("-");
privateJButtonmul=newJButton("x");
privateJButtondiv=newJButton("/");
privateJButtonequ=newJButton("=");
privateJButtoncle=newJButton("C");//清除
privateJTextFieldspace=newJTextField(15);
publicvoidinit(){
JPaneltext=newJPanel();
text.setLayout(newFlowLayout());
text.add(space);
JPanelbuttons=newJPanel();
buttons.setLayout(newGridLayout(5,4));
buttons.add(num9);
buttons.add(num8);
buttons.add(num7);
buttons.add(plu);
buttons.add(num6);
buttons.add(num5);
buttons.add(num4);
buttons.add(min);
buttons.add(num3);
buttons.add(num2);
buttons.add(num1);
buttons.add(mul);
buttons.add(num0);
buttons.add(cle);
buttons.add(equ);
buttons.add(div);
(num9).addActionListener(this);
(num8).addActionListener(this);
(num7).addActionListener(this);
(num6).addActionListener(this);
(num5).addActionListener(this);
(num4).addActionListener(this);
(num3).addActionListener(this);
(num2).addActionListener(this);
(num1).addActionListener(this);
(num0).addActionListener(this);
(plu).addActionListener(this);
(min).addActionListener(this);
(mul).addActionListener(this);
(div).addActionListener(this);
(equ).addActionListener(this);
(cle).addActionListener(this);
setLayout(newBorderLayout());
add("North",text);
add("South",buttons);
space.setText("0");
}
publicvoidactionPerformed(ActionEvente){
if(e.getSource()==num9){
if(i==true){
space.setText("9");
i=false;
}else
space.setText(space.getText()+'9');
}
if(e.getSource()==num8){
if(i==true){
space.setText("8");
i=false;
}else
space.setText(space.getText()+'8');
}
if(e.getSource()==num7){
if(i==true){
space.setText("7");
i=false;
}else
space.setText(space.getText()+'7');
}
if(e.getSource()==num6){
if(i==true){
space.setText("6");
i=false;
}else
space.setText(space.getText()+'6');
}
if(e.getSource()==num5){
if(i==true){
space.setText("5");
i=false;
}else
space.setText(space.getText()+'5');
}
if(e.getSource()==num4){
if(i==true){
space.setText("4");
i=false;
}else
space.setText(space.getText()+'4');
}
if(e.getSource()==num3){
if(i==true){
space.setText("3");
i=false;
}else
space.setText(space.getText()+'3');
}
if(e.getSource()==num2){
if(i==true){
space.setText("2");
i=false;
}else
space.setText(space.getText()+'2');
}
if(e.getSource()==num1){
if(i==true){
space.setText("1");
i=false;
}else
space.setText(space.getText()+'1');
}
if(e.getSource()==num0){
if(i==true){
space.setText("0");
i=false;
}else
space.setText(space.getText()+'0');
}
if(e.getSource()==plu){
space.setText(space.getText()+'+');
i=false;
}
if(e.getSource()==min){
space.setText(space.getText()+'-');
i=false;
}
if(e.getSource()==mul){
space.setText(space.getText()+'*');
i=false;
}
if(e.getSource()==div){
space.setText(space.getText()+'/');
i=false;
}
if(e.getSource()==equ){
space.setText(String.valueOf(Calculator(space.getText())));
i=true;
}
if(e.getSource()==cle){
space.setText("0");
i=true;
}
}
publicdoubleCalculator(Stringf)//科學計算
{
inti=0,j=0,k;
charc;
StringBuffers=newStringBuffer();
s.append(f);
s.append('=');
Stringformula=s.toString();
char[]anArray;
anArray=newchar[50];
Stack<Character>mystack=newStack<Character>();
while(formula.charAt(i)!='='){
c=formula.charAt(i);
switch(c){
case'+':
case'-':
while(!mystack.empty()&&mystack.peek().charValue()!='('){
anArray[j++]=mystack.pop().charValue();
}
mystack.push(newCharacter(c));
i++;
break;
case'*':
case'/':
while(!mystack.empty()
&&(mystack.peek().charValue()=='*'||mystack.peek()
.charValue()=='/')){
anArray[j++]=mystack.pop().charValue();
}
mystack.push(newCharacter(c));
i++;
break;
case'':
i++;
break;
default:
while((c>='0'&&c<='9')||c=='.'){
anArray[j++]=c;
i++;
c=formula.charAt(i);
}
anArray[j++]='#';
break;
}
}
while(!(mystack.empty()))
anArray[j++]=mystack.pop().charValue();
i=0;
intcount;
doublea,b,d;
Stack<Double>mystack1=newStack<Double>();
while(i<j){
c=anArray[i];
switch(c){
case'+':
a=mystack1.pop().doubleValue();
b=mystack1.pop().doubleValue();
d=b+a;
mystack1.push(newDouble(d));
i++;
break;
case'-':
a=mystack1.pop().doubleValue();
b=mystack1.pop().doubleValue();
d=b-a;
mystack1.push(newDouble(d));
i++;
break;
case'*':
a=mystack1.pop().doubleValue();
b=mystack1.pop().doubleValue();
d=b*a;
mystack1.push(newDouble(d));
i++;
break;
case'/':
a=mystack1.pop().doubleValue();
b=mystack1.pop().doubleValue();
if(a!=0){
d=b/a;
mystack1.push(newDouble(d));
i++;
}else{
System.out.println("Error!");
}
break;
default:
d=0;
count=0;
while((c>='0'&&c<='9')){
d=10*d+c-'0';
i++;
c=anArray[i];
}
if(c=='.'){
i++;
c=anArray[i];
while((c>='0'&&c<='9')){
count++;
d=d+(c-'0')/Math.pow(10,count);
i++;
c=anArray[i];
}
}
if(c=='#')
mystack1.push(newDouble(d));
i++;
break;
}
}
return(mystack1.peek().doubleValue());
}
}
你看看這個合適不?
Ⅷ 求一個用JAVA編寫的計算器程序(1)實現簡單加、減、乘、除的運算。 (
public
MyCalculator()
{
f
=
new
JFrame("計算器ByMdou");
Container
contentPane
=
f.getContentPane();
/****************菜單的創建開始**************************************/
JMenuBar
mBar
=
new
JMenuBar();
mBar.setOpaque(true);
mEdit
=
new
JMenu("編輯(E)");
mEdit.setMnemonic(KeyEvent.VK_E);
mCopy
=
new
JMenuItem("復制(C)");
mEdit.add(mCopy);
mPaste
=
new
JMenuItem("粘貼(P)");
mEdit.add(mPaste);
mView
=
new
JMenu("查看(V)");
mView.setMnemonic(KeyEvent.VK_V);
mView.add(new
JMenuItem("標准型"));
mView.add(new
JMenuItem("科學型"));
mView.addSeparator();
mView.add(new
JMenuItem("查看分組"));
mHelp
=
new
JMenu("幫助(H)");
mHelp.setMnemonic(KeyEvent.VK_H);
mHelp.add(new
JMenuItem("幫助主題"));
mHelp.addSeparator();
mHelp.add(new
JMenuItem("關於計算器"));
mBar.add(mEdit);
mBar.add(mView);
mBar.add(mHelp);
f.setJMenuBar(mBar);
contentPane.setLayout(new
BorderLayout
());
JPanel
pTop
=
new
JPanel();
tResult
=
new
JTextField("0.",26);
tResult.setHorizontalAlignment(JTextField.RIGHT
);
tResult.setEditable(false);
pTop.add(tResult);
contentPane.add(pTop,BorderLayout.NORTH);
JPanel
pBottom
=
new
JPanel();
pBottom.setLayout(new
BorderLayout());
JPanel
pLeft
=
new
JPanel();
pLeft.setLayout(new
GridLayout(5,1,3,3));
bM
=
new
JButton("
");
bM.setEnabled(false);
pLeft.add(bM);
bOther
=
new
JButton("MC");
bOther.addActionListener(this);
bOther.setForeground(Color.RED);
bOther.setMargin(new
Insets(3,2,3,2));
pLeft.add(bOther);
bOther
=
new
JButton("MR");
bOther.addActionListener(this);
bOther.setForeground(Color.RED);
bOther.setMargin(new
Insets(3,2,3,2));
pLeft.add(bOther);
bOther
=
new
JButton("MS");
bOther.addActionListener(this);
bOther.setForeground(Color.RED);
bOther.setMargin(new
Insets(3,2,3,2));
pLeft.add(bOther);
bOther
=
new
JButton("M+");
bOther.addActionListener(this);
bOther.setForeground(Color.RED);
bOther.setMargin(new
Insets(3,2,3,2));
pLeft.add(bOther);
Ⅸ 採用java語言編寫一個計算器,該計算器能對正數、負數(這里的正數、負數包括小數)進行加、減、乘、除運
import java.awt.*;
import java.awt.event.*;
public class Calculator implements ActionListener
{
Frame f;
MenuBar mb1;
Menu mf1,me1,mh1,md1;
Panel p1,p2,p3;
TextField tf1,tf2;
Button b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16,b17,b18,b19,b20,b21,b22,b23,b24,b25,b26,b27;
int Ms=0;//用於標識M+,Ms
double m=0;//用於實現連續運算
double k=0;//用於實現負號
double cur=0;//用於保存記憶的值
double k1;//用於實現Backspace
public Calculator()
{
f=new Frame("計算器散咐雹");
f.setSize(260,200);
f.setLocation(320,320);
f.setLayout(new BorderLayout());
f.setBackground(Color.lightGray);
tf1=new TextField(30);
tf1.setEditable(false);
tf1.setBackground(Color.WHITE);
f.add(tf1,BorderLayout.CENTER);
p1=new Panel(new BorderLayout());
f.add(p1,BorderLayout.SOUTH);
tf2=new TextField(2);
tf2.setEditable(false);
b1=new Button("BackSpace");
b1.setForeground(Color.RED);
b2=new Button(" CE ");
b2.setForeground(Color.RED);
b3=new Button(" C "沖帆);
b3.setForeground(Color.RED);
b2.addActionListener(this);
b3.addActionListener(this);
b1.addActionListener(this);
p2=new Panel(new FlowLayout(FlowLayout.RIGHT));
p2.add(tf2);
p2.add(b1);
p2.add(b2);
p2.add(b3);
b24=new Button("MC");
b24.setForeground(Color.RED);
b24.addActionListener(this);
b25=new Button("簡團MR");
b25.setForeground(Color.RED);
b25.addActionListener(this);
b26=new Button("MS");
b26.setForeground(Color.RED);
b26.addActionListener(this);
b27=new Button("M+");
b27.setForeground(Color.RED);
b27.addActionListener(this);
b19=new Button("/");
b19.setForeground(Color.RED);
b19.addActionListener(this);
b18=new Button("*");
b18.setForeground(Color.RED);
b18.addActionListener(this);
b17=new Button("-");
b17.setForeground(Color.RED);
b17.addActionListener(this);
b16=new Button("+");
b16.setForeground(Color.RED);
b16.addActionListener(this);
b14=new Button("+/-");
b14.addActionListener(this);
b15=new Button(".");
b15.addActionListener(this);
b20=new Button("sqrt");
b20.addActionListener(this);
b23=new Button("%");
b23.addActionListener(this);
b21=new Button("1/x");
b21.addActionListener(this);
b22=new Button("=");
b22.setForeground(Color.RED);
b22.addActionListener(this);
b4=new Button("7");
b5=new Button("8");
b6=new Button("9");
b7=new Button("4");
b8=new Button("5");
b9=new Button("6");
b10=new Button("1");
b11=new Button("2");
b12=new Button("3");
b13=new Button("0");
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
b7.addActionListener(this);
b8.addActionListener(this);
b9.addActionListener(this);
b10.addActionListener(this);
b11.addActionListener(this);
b12.addActionListener(this);
b13.addActionListener(this);
p3=new Panel(new GridLayout(4,6,2,2));
p3.add(b24);
p3.add(b4);
p3.add(b5);
p3.add(b6);
p3.add(b21);
p3.add(b19);
p3.add(b20);
p3.add(b25);
p3.add(b7);
p3.add(b8);
p3.add(b9);
p3.add(b18);
p3.add(b23);
p3.add(b26);
p3.add(b10);
p3.add(b11);
p3.add(b12);
p3.add(b17);
p3.add(b21);
p3.add(b27);
p3.add(b13);
p3.add(b14);
p3.add(b15);
p3.add(b16);
p3.add(b22);
p1.add(p2,BorderLayout.NORTH);
p1.add(p3,BorderLayout.CENTER);
f.add(p1,BorderLayout.SOUTH);
f.addWindowListener(new WinClose());
f.setVisible(true);
tf1.setText("");
addmyMenu();
}
public void addmyMenu()
{
mb1 = new MenuBar(); //生成一個菜單欄
f.setMenuBar(mb1); //框架f上添加菜單欄
mf1 = new Menu("編輯(E)"); //生成一個菜單
me1 = new Menu("查看(V)");
mh1 = new Menu("幫助(H)");
mb1.add(mf1); //菜單欄中加入菜單
mb1.add(me1);
mb1.add(mh1);
mf1.add(new MenuItem("復制")); //生成菜單項並加入到菜單
mf1.add(new MenuItem("粘貼"));
mf1.addActionListener(this); //為菜單注冊事件監聽程序
me1.add(new MenuItem("標准型"));
me1.add(new MenuItem("科學型"));
me1.addSeparator(); //加分隔線
me1.add(new MenuItem("數字分組"));
me1.addActionListener(this);
mh1.add(new MenuItem("幫助主題"));
mh1.add(new MenuItem("關於計算器"));
mh1.addActionListener(this);
}
int flag=0;//運算符有效標識
int num=0;//用於實現連續運算
double dot=0;//用於標識小數點
double first=0,second=0,result=0;//用於保存第一個數,第二個數和計算結果
double push;//用於標識是否有數字鍵按下
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b3)
{tf1.setText("0.");
num=0;
dot=0;
push=0;
flag=0;
first=0;}
else
if(e.getSource()==b4)
{
if(push==0.)
tf1.setText(e.getActionCommand());
else
tf1.setText(tf1.getText()+e.getActionCommand());
push=1;}
if(e.getSource()==b5)
{
if(push==0.)
tf1.setText(e.getActionCommand());
else
tf1.setText(tf1.getText()+e.getActionCommand());
push=1;}
if(e.getSource()==b6)
{
if(push==0.)
tf1.setText(e.getActionCommand());
else
tf1.setText(tf1.getText()+e.getActionCommand());
push=1;}
if(e.getSource()==b7)
{
if(push==0.)
tf1.setText(e.getActionCommand());
else
tf1.setText(tf1.getText()+e.getActionCommand());
push=1;}
if(e.getSource()==b8)
{
if(push==0.)
tf1.setText(e.getActionCommand());
else
tf1.setText(tf1.getText()+e.getActionCommand());
push=1;}
if(e.getSource()==b9)
{
if(push==0.)
tf1.setText(e.getActionCommand());
else
tf1.setText(tf1.getText()+e.getActionCommand());
push=1;}
if(e.getSource()==b10)
{
if(push==0.)
tf1.setText(e.getActionCommand());
else
tf1.setText(tf1.getText()+e.getActionCommand());
push=1;}
if(e.getSource()==b11)
{
if(push==0.)
tf1.setText(e.getActionCommand());
else
tf1.setText(tf1.getText()+e.getActionCommand());
push=1;}
if(e.getSource()==b12)
{
if(push==0.)
tf1.setText(e.getActionCommand());
else
tf1.setText(tf1.getText()+e.getActionCommand());
push=1;}
if(e.getSource()==b13)
{
if(push==0.)
tf1.setText(e.getActionCommand());
else
tf1.setText(tf1.getText()+e.getActionCommand());}
if(e.getSource()==b26||e.getSource()==b27)
{
tf2.setText("M");
cur=Double.parseDouble(tf1.getText());
Ms=1;
}
if(e.getSource()==b25)
{
if(Ms==1)
tf1.setText(Double.toString(cur));
else
tf1.setText("0.");
}
if(e.getSource()==b24)
{
tf2.setText(" ");
Ms=0;
}
if(e.getSource()==b14)
{
k=Double.parseDouble(tf1.getText());
k=-k;
tf1.setText(Double.toString(k));
}
if(e.getSource()==b15)
{
push=1;
if(dot==0)
tf1.setText(tf1.getText()+e.getActionCommand());
else
tf1.setText(tf1.getText());
dot=1;}
if(e.getSource()==b16)
{
flag=1;
first=Double.parseDouble(tf1.getText());
dot=0;
push=0;
}
if(e.getSource()==b17)
{
flag=2;
first=Double.parseDouble(tf1.getText());
dot=0;
push=0;
}
if(e.getSource()==b18)
{
flag=3;
first=Double.parseDouble(tf1.getText());
dot=0;
push=0;
}
if(e.getSource()==b19)
{
flag=4;
first=Double.parseDouble(tf1.getText());
dot=0;
push=0;
}
if(e.getSource()==b21)
{
flag=5;
first=Double.parseDouble(tf1.getText());
dot=0;
push=0;
}
if(e.getSource()==b23)
{
flag=6;
first=Double.parseDouble(tf1.getText());
dot=0;
push=0;
}
if(e.getSource()==b20)
{
flag=7;
first=Double.parseDouble(tf1.getText());
dot=0;
push=0;
}
if(e.getSource()==b22)
{
second=Double.parseDouble(tf1.getText());
if(num==0)
m=second;
num=1;
switch(flag)
{
case 0: break;
case 1: result=first+second;
first=m;
tf1.setText(String.valueOf(result));
break;
case 2:second=m;
result=first-second;
first=result;
tf1.setText(String.valueOf(result));
break;
case 3:result=first*second;
first=m;
tf1.setText(String.valueOf(result));
break;
case 4:if(second==0)
tf1.setText("除數不能為0");
else
{second=m;
result=first/second;
first=result;
tf1.setText(String.valueOf(result));}
break;
case 5:if(first==0)
tf1.setText("0沒有倒數");
else
{result=1/first;
first=result;
tf1.setText(String.valueOf(result));}
break;
case 6:result=first/100;
first=result;
tf1.setText(String.valueOf(result));
break;
case 7:if(first<0)
tf1.setText("負數不能開方");
else{result=Math.sqrt(first);
first=result;
tf1.setText(String.valueOf(result));}
break;
}
dot=0;
push=0;
}
if(e.getSource()==b2)
{
tf1.setText("0.");
}
if(e.getSource()==b1)
{
k1=Double.parseDouble(tf1.getText());
if(k1==0)
tf1.setText(Double.toString(k1));
String s=tf1.getText();
int i;
i=s.length();
s=s.substring(0,i-1);
i=i-1;
if(i==0)
tf1.setText("0.");
else
tf1.setText(s);
push=0;
dot=0;
}
}
public static void main(String arg[])
{
new Calculator();
}
}
class WinClose extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
Ⅹ 用JAVA編寫的科學計算器源代碼
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class Counter extends WindowAdapter
{
static JFrame f=new JFrame("計算器");
static JTextField text1=new JTextField("0.");
static String source="";
static String cal="";
static String object="";
static boolean flag=false;
static boolean flag1=true;
static boolean flag2=false;
public void init()
{
try
{
Container c=f.getContentPane();
JPanel pan1=new JPanel();
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
JButton b6=new JButton("6");
JButton b7=new JButton("7");
JButton b8=new JButton("8");
JButton b9=new JButton("9");
JButton b0=new JButton("0");
JButton b11=new JButton("+");
JButton b12=new JButton("-");
JButton b13=new JButton("*");
JButton b14=new JButton("/");
JButton b15=new JButton(".");
JButton b16=new JButton("=");
JButton bclar=new JButton("清零");
text1.setHorizontalAlignment(JTextField.RIGHT);
c.add(text1,"North");
c.add(pan1);
A aa=new A();
Result re=new Result();
Opertion op=new Opertion();
Clar cl=new Clar();
b1.addActionListener(aa);
b2.addActionListener(aa);
b3.addActionListener(aa);
b4.addActionListener(aa);
b5.addActionListener(aa);
b6.addActionListener(aa);
b7.addActionListener(aa);
b8.addActionListener(aa);
b9.addActionListener(aa);
b0.addActionListener(aa);
b11.addActionListener(op);
b12.addActionListener(op);
b13.addActionListener(op);
b14.addActionListener(op);
b16.addActionListener(re);
b15.addActionListener(aa);
bclar.addActionListener(cl);
pan1.add(b1);
pan1.add(b2);
pan1.add(b3);
pan1.add(b11);
pan1.add(b4);
pan1.add(b5);
pan1.add(b6);
pan1.add(b12);
pan1.add(b7);
pan1.add(b8);
pan1.add(b9);
pan1.add(b13);
pan1.add(b0);
pan1.add(b15);
pan1.add(b16);
pan1.add(b14);
pan1.add(bclar);
f.setSize(200,220);
f.setVisible(true);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
class A implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String a=text1.getText();
String s=e.getActionCommand();
if(a.equals("0.")||a.equals("+")||a.equals("-")||a.equals("*")||a.equals("/"))
text1.setText(s);
else {
if(flag2)
{
text1.setText(s);
flag2=false;
}
else
text1.setText(a+s);
}
}
}
class Opertion implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
cal=e.getActionCommand();
if(flag1==true)
source=text1.getText();
text1.setText(cal);
flag1=false;
flag=true;
}
}
class Result implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
double num1;
num1=Double.parseDouble(source);
object=text1.getText();
double num2;
num2=Double.parseDouble(object);
double result=0;
if(cal.equals("+"))
result=num1+num2;
if(cal.equals("-"))
result=num1-num2;
if(cal.equals("*"))
result=num1*num2;
if(cal.equals("/"))
if(num2==0)
text1.setText("除數不能為0");
else
result=num1/num2;
String s1=Double.toString(result);
text1.setText(s1);
flag1=true;
flag2=true;
}
}
class Clar implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
text1.setText("0.");
}
}
public static void main(String[] args)
{
Counter count=new Counter();
count.init();
}
public void windowClosing(WindowEvent e){
System.exit(1);
}
public void windowOpened(WindowEvent e){}
public void windowIconified(WindowEvent e){}
public void windowDeiconified(WindowEvent e){}
public void windowClosed(WindowEvent e){}
public void windowActivated(WindowEvent e){}
public void windowDeactivated(WindowEvent e){}
}