① 編寫java程序簡單計算器
主要涉及的知識點: 類的寫法, 以及方法的調用 .建議多做練習. 如果有看不懂的地方. 可以繼續追問,一起討論.
參考代碼如下
//Number類
classNumber{
privateintn1;//私有的整型數據成員n1
privateintn2;//私有的整型數據成員n2
//通過構造函數給n1和n2賦值
publicNumber(intn1,intn2){
this.n1=n1;
this.n2=n2;
}
//加法
publicintaddition(){
returnn1+n2;
}
//減法
publicintsubtration(){
returnn1-n2;
}
//乘法
publicintmultiplication(){
returnn1*n2;
}
//除法(可能除不盡,所以使用double作為返回類型)
publicdoubledivision(){
returnn1*1.0/n2;//通過n1*1.0把計算結果轉換成double類型.
}
}
//Exam4類
publicclassExam4{
publicstaticvoidmain(String[]args){
Numbernumber=newNumber(15,6);//創建Number類的對象
//下面的是調用方法得到返回值進行輸出顯示
System.out.println("加法"+number.addition());
System.out.println("減法"+number.subtration());
System.out.println("乘法"+number.multiplication());
System.out.println("除法"+number.division());
}
}
② JAVA在WEB上的應用——實現簡易計算器
建立14個按鈕,按鈕的名字都要Command1,設置Index屬性,0~9分別對應數字0~9,10為小數點,11為等號,12~14分別對應+、-、*和/。
2、輸入如下代碼:
Dim Num1, Num2 As Single
Dim StrNum1, StrNum2 As String
Dim FirstNum As Boolean
Dim PointFlag As Boolean
Dim Runsign As Integer
Dim SignFlag As Boolean
Private Sub Command1_Click(Index As Integer)
Select Case Index
Case 0 To 9
If FirstNum Then
StrNum1 = Str(Index)
FirstNum = False
Else
StrNum1 = LTrim(StrNum1) + LTrim(Str(Index))
End If
Text1.Text = Val(StrNum1)
Case 10
If Not PointFlag Then
If FirstNum Then
StrNum1 = "0."
FirstNum = False
Else
StrNum1 = LTrim(StrNum1) + LTrim(".")
End If
Else
Exit Sub
End If
PointFlag = True
Text1.Text = Val(StrNum1)
Case 12 To 15
FirstNum = True
PointFlag = False
If SignFlag Then
Call Run
Else
SignFlag = True
StrNum2 = StrNum1
StrNum1 = ""
End If
Runsign = Index - 11
Case 11
On Error Resume Next
If Not SignFlag Then
Text1.Text = StrNum1
equal = Val(StrNum1)
FirstNum = True
PointFlag = False
Else
Call Run
SignFlag = False
End If
Case Else
Call ClearData
End Select
End Sub
Private Sub Form_Load()
If App.PrevInstance Then MsgBox "請不要多次運行此程序,謝謝!", vbAbortRetryIgnore: Unload Me
Num1 = 0
Num2 = 0
StrNum1 = ""
StrNum2 = ""
FirstNum = True
PointFlag = False
Runsign = 0
SignFlag = False
End Sub
Sub Run()
On Error Resume Next
Dim equal As Single
Dim equal2 As Double
Num1 = Val(StrNum2)
Num2 = Val(StrNum1)
Select Case Runsign
Case 1
equal = Num1 + Num2
If Num1 >= 65536 Or Num2 >= 65536 Or equal >= 65536 Then
equal = 0
equal2 = Num1 + Num2
End If
Case 2
equal = Num1 - Num2
If Num1 >= 65536 Or Num2 >= 65536 Or equal >= 65536 Then
equal = 0
equal2 = Num1 - Num2
End If
Case 3
equal = Num1 * Num2
If Num1 >= 65536 Or Num2 >= 65536 Or equal >= 65536 Then
equal = 0
equal2 = Num1 * Num2
End If
Case 4
equal = Num1 / Num2
If Num1 >= 65536 Or Num2 >= 65536 Or equal >= 65536 Then
equal = 0
equal2 = Num1 / Num2
End If
End Select
If equal = 0 Then a = equal2 Else a = equal
StrNum2 = Str(a)
StrNum1 = StrNum2
Text1.Text = Val(StrNum2)
End Sub
Sub ClearData()
Num1 = 0
Num2 = 0
StrNum1 = ""
StrNum2 = ""
FirstNum = True
PointFlag = False
Runsign = 0
SignFlag = False
Text1.Text = 0
End Sub
③ 怎麼做一個JAVA計算器
classCalcBtnextendsJButton{
=1L;
Fontfont=newFont("仿宋",1,22);
publicCalcBtn(Stringtext,Colorcolor){
super(text);
setForeground(color);
setFont(font);
setMargin(newInsets(0,0,0,0));
setFocusable(false);
}
}
@SuppressWarnings("serial")
{
publicstaticvoidmain(String[]args){
try{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}catch(Exceptionex){
ex.printStackTrace();
}
newCalcFrame().setVisible(true);
}
privateCalcBtnbtn_1=newCalcBtn("1",Color.BLUE);
privateCalcBtnbtn_2=newCalcBtn("2",Color.BLUE);
privateCalcBtnbtn_3=newCalcBtn("3",Color.BLUE);
privateCalcBtnbtn_4=newCalcBtn("4",Color.BLUE);
privateCalcBtnbtn_5=newCalcBtn("5",Color.BLUE);
privateCalcBtnbtn_6=newCalcBtn("6",Color.BLUE);
privateCalcBtnbtn_7=newCalcBtn("7",Color.BLUE);
privateCalcBtnbtn_8=newCalcBtn("8",Color.BLUE);
privateCalcBtnbtn_9=newCalcBtn("9",Color.BLUE);
privateCalcBtnbtn_0=newCalcBtn("0",Color.BLUE);
privateCalcBtnbtn_back=newCalcBtn("←",Color.red);
privateCalcBtnbtn_c=newCalcBtn("C",Color.red);
privateCalcBtnbtn_ce=newCalcBtn("CE",Color.red);
privateCalcBtnbtn_sub=newCalcBtn("-",Color.red);
privateCalcBtnbtn_multi=newCalcBtn("*",Color.red);
privateCalcBtnbtn_div=newCalcBtn("/",Color.red);
privateCalcBtnbtn_add=newCalcBtn("+",Color.red);
privateCalcBtnbtn_sqrt=newCalcBtn("sqrt",Color.BLUE);
privateCalcBtnbtn_mod=newCalcBtn("%",Color.BLUE);
privateCalcBtnbtn_x=newCalcBtn("1/x",Color.BLUE);
privateCalcBtnbtn_res=newCalcBtn("=",Color.red);
privateCalcBtnbtn_point=newCalcBtn(".",Color.red);
privateCalcBtnbtn_flag=newCalcBtn("+/-",Color.BLUE);
privateJButtonbtn_mem=newJButton("");
privateCalcBtnbtn_m=newCalcBtn("M+",Color.BLUE);
privateCalcBtnbtn_mc=newCalcBtn("MC",Color.BLUE);
privateCalcBtnbtn_mr=newCalcBtn("MR",Color.BLUE);
privateCalcBtnbtn_ms=newCalcBtn("MS",Color.BLUE);
JPanelpan_jtf=newJPanel();
JPanelpan_back=newJPanel();
JPanelpan_mem=newJPanel();
JPanelpan_num=newJPanel();
JTextFieldjtf_res=newJTextField();
//
privateJMenuBarmenuBar=newJMenuBar();
privateJMenumenu_edit=newJMenu("編輯(E)");
privateJMenumenu_view=newJMenu("查看(V)");
privateJMenumenu_help=newJMenu("幫助(H)");
privateJMenuItemeditMenu_=newJMenuItem("復制(C)");
privateJMenuItemeditMenu_paste=newJMenuItem("粘貼(P)");
_standard=newJCheckBoxMenuItem(
"標准型(T)");
_science=newJCheckBoxMenuItem("科學型(S)");
_grouping=newJCheckBoxMenuItem(
"數字分組(I)");
privateJMenuItemhelpmenu_help=newJMenuItem("幫助主題(H)");
privateJMenuItemhelpmenu_about=newJMenuItem("關於計算器(A)");
Stringsave1,save2;
BigDecimalop1,op2;
booleanisBigDecimal=false;
intpreOp,currentOp=0;
StringBufferstr=newStringBuffer();
publicCalcFrame(){
this.setTitle("於☆弦");
this.setResizable(false);
setSize(444,390);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setJMenuBar(menuBar);
setLayout(null);
init_pan_jtf();
init_menuBar();
init_pan_back();
init_pan_mem();
init_pan_num();
getContentPane().add(pan_jtf);
getContentPane().add(pan_back);
getContentPane().add(pan_mem);
getContentPane().add(pan_num);
}
privatevoidinit_menuBar(){
menuBar.add(menu_edit);
menuBar.add(menu_view);
menuBar.add(menu_help);
menu_edit.add(editMenu_);
menu_edit.add(editMenu_paste);
menu_view.add(viewmenu_standard);
menu_view.add(viewmenu_science);
menu_view.addSeparator();
menu_view.add(viewmenu_grouping);
menu_help.add(helpmenu_help);
menu_help.addSeparator();
menu_help.add(helpmenu_about);
menu_edit.setMnemonic('E');
menu_view.setMnemonic('V');
menu_help.setMnemonic('H');
editMenu_.setMnemonic('C');
editMenu_.setAccelerator(KeyStroke.getKeyStroke('C',
InputEvent.CTRL_MASK));
editMenu_paste.setMnemonic('P');
editMenu_paste.setAccelerator(KeyStroke.getKeyStroke('V',
InputEvent.CTRL_MASK));
viewmenu_standard.setMnemonic('T');
viewmenu_science.setMnemonic('S');
viewmenu_grouping.setMnemonic('I');
helpmenu_help.setMnemonic('H');
helpmenu_about.setMnemonic('A');
}
publicvoidinit_pan_back(){
pan_back.setSize(340,40);
pan_back.setLocation(85,60);
pan_back.setLayout(newGridLayout(1,3,5,0));
pan_back.add(btn_back);
pan_back.add(btn_ce);
pan_back.add(btn_c);
btn_back.addActionListener(newActionListener(){
publicvoidactionPerformed(ActionEvente){
if(!jtf_res.getText().trim().equals("0.")){
if(str.length()!=1&&str.length()!=0){
jtf_res.setText(str.delete(str.length()-1,
str.length()).toString());
}else{
jtf_res.setText("0.");
str.setLength(0);
}
}
op2=newBigDecimal(jtf_res.getText().trim());
}
});
btn_c.addActionListener(newActionListener(){
publicvoidactionPerformed(ActionEvente){
jtf_res.setText("0.");
op1=op2=newBigDecimal(0);
str.replace(0,str.length(),"");
preOp=currentOp=0;
}
});
btn_ce.addActionListener(newActionListener(){
publicvoidactionPerformed(ActionEvente){
jtf_res.setText("0.");
}
});
}
publicvoidinit_pan_jtf(){
jtf_res.setHorizontalAlignment(JTextField.RIGHT);
jtf_res.setFont(newFont("仿宋",0,20));
jtf_res.setText("0.");
jtf_res.setEditable(false);
//jtf_res.setFocusable(false);
pan_jtf.setSize(420,40);
pan_jtf.setLocation(10,5);
pan_jtf.setLayout(newBorderLayout());
pan_jtf.add(jtf_res);
}
publicvoidinit_pan_mem(){
pan_mem.setSize(60,270);
pan_mem.setLocation(10,60);
pan_mem.setLayout(newGridLayout(5,1,0,5));
pan_mem.add(btn_mem);
btn_mem.setEnabled(false);
pan_mem.add(btn_mc);
pan_mem.add(btn_mr);
pan_mem.add(btn_ms);
pan_mem.add(btn_m);
}
publicvoidinit_pan_num(){
pan_num.setSize(340,220);
pan_num.setLocation(85,110);
pan_num.setLayout(newGridLayout(4,5,5,5));
pan_num.add(btn_7);
pan_num.add(btn_8);
pan_num.add(btn_9);
pan_num.add(btn_div);
pan_num.add(btn_sqrt);
pan_num.add(btn_4);
pan_num.add(btn_5);
pan_num.add(btn_6);
pan_num.add(btn_multi);
pan_num.add(btn_mod);
pan_num.add(btn_1);
pan_num.add(btn_2);
pan_num.add(btn_3);
pan_num.add(btn_sub);
pan_num.add(btn_x);
pan_num.add(btn_0);
pan_num.add(btn_flag);
pan_num.add(btn_point);
pan_num.add(btn_add);
pan_num.add(btn_res);
btn_1.addActionListener(this);
btn_2.addActionListener(this);
btn_3.addActionListener(this);
btn_4.addActionListener(this);
btn_5.addActionListener(this);
btn_6.addActionListener(this);
btn_7.addActionListener(this);
btn_8.addActionListener(this);
btn_9.addActionListener(this);
btn_0.addActionListener(this);
btn_sub.addActionListener(this);
btn_multi.addActionListener(this);
btn_div.addActionListener(this);
btn_add.addActionListener(this);
btn_sqrt.addActionListener(this);
btn_x.addActionListener(this);
btn_res.addActionListener(this);
btn_point.addActionListener(this);
btn_flag.addActionListener(this);
//btn_mod.addActionListener(this);
}
@Override
publicvoidactionPerformed(ActionEvente){
Strings=e.getActionCommand();
BigDecimali=newBigDecimal(1);
Stringtemp=jtf_res.getText().trim();
BigDecimaltemp1=newBigDecimal(temp);
if(e.getSource()==btn_flag){
BigDecimaltemp3=newBigDecimal(jtf_res.getText());
BigDecimaltemp4=newBigDecimal(-1);
BigDecimaltemp5=temp3.multiply(temp4);
jtf_res.setText(""+temp5);
}elseif(s.equals("1/x")){
jtf_res.setText(""+i.divide(temp1,newMathContext(30)));
}elseif(s.equals("sqrt")){
jtf_res.setText(""+temp1.multiply(temp1));
}elseif(s.equals("+")){
str.setLength(0);
if(currentOp==0){
preOp=currentOp=1;
op2=newBigDecimal("0");
jtf_res.setText(""+op1);
}else{
currentOp=preOp;
preOp=1;
switch(currentOp){
case1:
op1=op1.add(op2);
jtf_res.setText(""+op1);
break;
case2:
op1=op1.subtract(op2);
jtf_res.setText(""+op1);
break;
case3:
op1=op1.multiply(op2);
jtf_res.setText(""+op1);
break;
case4:
op1=op1.divide(op2,newMathContext(30));
jtf_res.setText(""+op1);
break;
}
}
}elseif(s.equals("-")){
str.setLength(0);
if(currentOp==0){
preOp=currentOp=2;
jtf_res.setText(""+op1);
}else{
currentOp=preOp;
preOp=2;
switch(currentOp){
case1:
op1=op1.add(op2);
jtf_res.setText(""+op1);
break;
case2:
op1=op1.subtract(op2);
jtf_res.setText(""+op1);
break;
case3:
op1=op1.multiply(op2);
jtf_res.setText(""+op1);
break;
case4:
op1=op1.divide(op2,newMathContext(30));
jtf_res.setText(""+op1);
break;
}
}
}elseif(s.equals("*")){
str.setLength(0);
if(currentOp==0){
preOp=currentOp=3;
jtf_res.setText(""+op1);
}else{
currentOp=preOp;
preOp=3;
switch(currentOp){
case1:
op1=op1.add(op2);
jtf_res.setText(""+op1);
break;
case2:
op1=op1.subtract(op2);
jtf_res.setText(""+op1);
break;
case3:
op1=op1.multiply(op2);
jtf_res.setText(""+op1);
break;
case4:
op1=op1.divide(op2,newMathContext(30));
jtf_res.setText(""+op1);
break;
}
}
}elseif(s.equals("/")){
str.setLength(0);
if(currentOp==0){
preOp=currentOp=4;
jtf_res.setText(""+op1);
}else{
currentOp=preOp;
preOp=4;
switch(currentOp){
case1:
op1=op1.add(op2);
jtf_res.setText(""+op1);
break;
case2:
op1=op1.subtract(op2);
jtf_res.setText(""+op1);
break;
case3:
op1=op1.multiply(op2);
jtf_res.setText(""+op1);
break;
case4:
op1=op1.divide(op2,newMathContext(30));
jtf_res.setText(""+op1);
break;
}
}
}elseif(s.equals("=")){
if(currentOp==0){
str.setLength(0);
jtf_res.setText(""+op2);
}else{
str.setLength(0);
currentOp=preOp;
switch(currentOp){
case1:
op1=op1.add(op2);
jtf_res.setText(""+op1);
break;
case2:
op1=op1.subtract(op2);
jtf_res.setText(""+op1);
break;
case3:
op1=op1.multiply(op2);
jtf_res.setText(""+op1);
break;
case4:
op1=op1.divide(op2,newMathContext(30));
jtf_res.setText(""+op1);
break;
}
currentOp=0;
op2=newBigDecimal("0");
}
}elseif(s.equals(".")){
isBigDecimal=true;
if(jtf_res.getText().trim().indexOf('.')!=-1)
;
else{
if(jtf_res.getText().trim().equals("0")){
str.setLength(0);
jtf_res.setText((str.append("0"+s)).toString());
}elseif(jtf_res.getText().trim().equals("")){
}else{
jtf_res.setText((str.append(s)).toString());
}
}
}elseif(s.equals("0")){
if(jtf_res.getText().trim().equals("0.")){
}else{
jtf_res.setText(str.append(s).toString());
op2=newBigDecimal(jtf_res.getText().trim());
}
}else{
jtf_res.setText(str.append(s).toString());
op2=newBigDecimal(jtf_res.getText().trim());
if(currentOp==0)
op1=op2;
}
}
}
④ 求JAVA用Eclipse寫個簡易的計算器。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Calculator extends JFrame implements ActionListener {
private final String[] KEYS = { "7", "8", "9", "c", "4", "5", "6",
"+", "1", "2", "3", "-", "0", "*", "/","=" };
//計算器上按鍵的顯示名
private JButton keys[] = new JButton[KEYS.length];
// 計算器上按鍵的按鈕
private JTextField resultText = new JTextField("0");
//計算結果文本框
private boolean firstDigit = true;
//標志用戶按的是否是整個表達式的第一個數字,或者是運算符後的第一個數字
private double resultNum = 0.0;
//計算的中間結果
private String operator = "=";
//當前運算的運算符
private boolean operateValidFlag = true; // 操作是否合法
////構造函數
public Calculator ()
{
super();
init(); //初始化計算器
this.setBackground(Color.lightGray); //設置計算器的背景顏色
this.setTitle("計算器");
this.setLocation(100,100);//在屏幕(100,100)坐標處顯示計算器
this.setResizable(false);//不許修改計算器的大小
this.setSize(300,250); //使計算器中各組件大小合適
}
////初始化計算器
private void init()
{
resultText.setHorizontalAlignment(JTextField.RIGHT); // 文本框中的內容採用右對齊方式
resultText.setEditable(false); // 不允許修改結果文本框
resultText.setBackground(Color.white); // 設置文本框背景顏色為白色
JPanel calckeysPanel = new JPanel();
//初始化計算器上按鍵的按鈕,將鍵放在一個畫板內
calckeysPanel.setLayout(new GridLayout(4, 4, 10, 15));//用網格布局器,4行,5列的網格,網格之間的水平方向間隔為10個象,垂直方向間隔為15個象素
calckeysPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));//添加畫板的邊框
for (int i = 0; i < KEYS.length; i++)
{
keys[i] = new JButton(KEYS[i]);
calckeysPanel.add(keys[i]);
}
//整體布局
getContentPane().setLayout(new BorderLayout(3, 5));
getContentPane().add("North", resultText);
getContentPane().add("Center", calckeysPanel);
//為各按鈕添加事件偵聽器
//都使用同一個事件偵聽,即本對象.本類的聲明中有implements ActionListener
for (int i = 0; i < KEYS.length; i++)
{
keys[i].addActionListener(this);
}
}
////處理事件
public void actionPerformed(ActionEvent e)
{
String label = e.getActionCommand();//獲取事件源的標簽
if (e.getSource()==keys[3])
{
handleC(); //用戶按了"C"鍵
}
else if ("0123456789.".indexOf(label) >= 0)
{
handleNumber(label);//用戶按了數字鍵或者小數點鍵
}
else
{
handleOperator(label); //用戶按了運算符鍵
}
}
////處理數字鍵被按下的事件
private void handleNumber(String key)
{
if (firstDigit) //輸入的第一個數字
{
resultText.setText(key);
}
else if ((key.equals(".")) && (resultText.getText().indexOf(".") < 0))
//輸入的是小數點,並且之前沒有小數點,則將小數點附在結果文本框的後面
{
resultText.setText(resultText.getText() + ".");
}
else if (!key.equals("."))
//如果輸入的不是小數點,則將數字附在結果文本框的後面
{
resultText.setText(resultText.getText() + key);
}
firstDigit = false; //以後輸入的肯定不是第一個數字了
}
////處理C鍵被按下的事件
private void handleC()
{
//初始化計算器的各種值
resultText.setText("0");
firstDigit = true;
operator = "=";
}
////處理運算符鍵被按下的事件
private void handleOperator(String key)
{
if (operator.equals("/")) //除法運算
{
if (getNumberFromText() == 0.0)
//如果當前結果文本框中的值等於0,操作不合法
{
operateValidFlag = false;
resultText.setText("除數不能為零");
}
else
{
resultNum /= getNumberFromText();
}
}
else if (operator.equals("+"))//加法運算
{
resultNum += getNumberFromText();
}
else if (operator.equals("-"))//減法運算
{
resultNum -= getNumberFromText();
}
else if (operator.equals("*")) //乘法運算
{
resultNum *= getNumberFromText();
}
else if (operator.equals("="))//賦值運算
{
resultNum = getNumberFromText();
}
if (operateValidFlag) //雙精度浮點數的運算
{
long t1;
double t2;
t1 = (long) resultNum;
t2 = resultNum - t1;
if (t2 == 0) {
resultText.setText(String.valueOf(t1));
} else {
resultText.setText(String.valueOf(resultNum));
}
}
operator = key;//運算符等於用戶按的按鈕
firstDigit = true;
operateValidFlag = true;
}
////從結果文本框中獲取數字
private double getNumberFromText()
{
double result = 0;
try
{
result = Double.valueOf(resultText.getText()).doubleValue();
}
catch (NumberFormatException e)
{}
return result;
}
public static void main(String args[])
{
Calculator calculator1 = new Calculator ();
calculator1.setVisible(true);
calculator1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
湊合寫了一個,不過這計算器功能真是少。
⑤ java編寫一個計算器類
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class Jisuanqi extends JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
Result result = new Result(); // 定義text的面板
Number_Key number_key = new Number_Key(); // 定義按鈕面板
// 當點擊按鈕+、-、*、/時,com = true
boolean com = false;
// 當i=0時說明是我們第一次輸入,字元串text不會累加
int i = 0;
// 存放text的內容
String text = "";
// 存放點擊按鈕+、-、*、/之前的數值
double defbutton = 0;
// +、-、*、/的代號分別為1,2,3,4
int symbol = 0;
// 構造函數
Jisuanqi() {
super("計算器"); // 設定標題
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 設定關閉窗體時退出程序
JPanel pane = new JPanel(); // 定義主面板
pane.setLayout(new BorderLayout());
setBounds(380, 220, 30, 80); // 前兩個參數是在屏幕上顯示的坐標,後兩個是大小
// 替換圖標
ImageIcon icon = new ImageIcon("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(); // 初始化窗體大小為正好盛放所有按鈕
}
// 各個按鈕觸發的事件
public void actionPerformed(ActionEvent e) {
/*
* 如果是點擊數字按鈕那麼先要判斷是否在此之前點擊了+、-、*、/、=,如果是那麼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");
}
} else if (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");
}
} else if (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");
}
} else if (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");
}
} else if (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");
}
} else if (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");
}
} else if (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");
}
} else if (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");
}
} else if (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;否則保持原來的數值不變
*/
else if (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");
}
}
}
} else if (e.getSource() == number_key.ce) {
result.text.setText("0");
i = 0;
com = true;
// text = "";
defbutton = 0;
}
/*
* 本程序不會讓一個數值中出現2個以上的小數點.具體做法是:判斷是否已經存在.存在就不添加, 不存在就添加.
*/
else if (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);
}
}
} // 獲得點擊+之前的數值
else if (e.getSource() == number_key.plus) {
com = true;
i = 0;
defbutton = Double.parseDouble(result.text.getText());
symbol = 1;
} // 獲得點擊-之前的數值
else if (e.getSource() == number_key.sub) {
com = true;
i = 0;
defbutton = Double.parseDouble(result.text.getText());
symbol = 2;
} // 獲得點擊*之前的數值
else if (e.getSource() == number_key.mul) {
com = true;
i = 0;
defbutton = Double.parseDouble(result.text.getText());
System.out.println(defbutton);
symbol = 3;
} // 獲得點擊/之前的數值
else if (e.getSource() == number_key.div) {
com = true;
i = 0;
defbutton = Double.parseDouble(result.text.getText());
symbol = 4;
} else if (e.getSource() == number_key.equal) {
switch (symbol) {
case 1: { // 計算加法
double ad = defbutton
+ Double.parseDouble(result.text.getText());
result.text.setText(ad + "");
i = 0;
text = "";
break;
}
case 2: { // 計算減法
double ad = defbutton
- Double.parseDouble(result.text.getText());
result.text.setText(String.valueOf(ad));
i = 0;
text = "";
break;
}
case 3: { // 計算乘法
double ad = defbutton
* Double.parseDouble(result.text.getText());
result.text.setText(ad + "");
i = 0;
text = "";
break;
}
case 4: { // 計算除法
double ad = 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")
public static void main(String[] args) {
Jisuanqi loveyou = new Jisuanqi();
loveyou.show();
}
}
// 計算器數字按鈕定義面板
class Number_Key extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
JButton zero = new JButton("0"); // 數字鍵0
JButton one = new JButton("1"); // 數字鍵1
JButton two = new JButton("2"); // 數字鍵2
JButton three = new JButton("3"); // 數字鍵3
JButton four = new JButton("4"); // 數字鍵4
JButton five = new JButton("5"); // 數字鍵5
JButton six = new JButton("6"); // 數字鍵6
JButton seven = new JButton("7"); // 數字鍵7
JButton eight = new JButton("8"); // 數字鍵8
JButton nine = new JButton("9"); // 數字鍵9
JButton plus = new JButton("+");
JButton sub = new JButton("-");
JButton mul = new JButton("*");
JButton div = new JButton("/");
JButton equal = new JButton("=");
JButton ce = new JButton("清零"); // 置零鍵
JButton point = new JButton(".");
Number_Key() {
setLayout(new GridLayout(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);
}
}
// 計算器顯示結果的窗體
class Result extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
// text先是輸入和結果
JTextField text = new JTextField("0");
@SuppressWarnings("deprecation")
Result() { // 講輸入的數字或得到的結果在text的右邊顯示
text.setHorizontalAlignment(SwingConstants.RIGHT);
text.enable(false); // 文本框不能編輯
setLayout(new BorderLayout()); // 設定布局管理器邊框布局
add(text, BorderLayout.CENTER); // text放置在窗體的中間
}
}
⑥ 用java編寫一個簡單的計算器類
這個是有界面的,自己改一些就可以了。。
---------------------------------------------
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
class Stack_Float
{
float nums[];
int top;
Stack_Float()
{
nums = new float[50];
top = -1;
}
boolean IsEmpty()
{
if (top == -1)
return true;
else
return false;
}
float Pop_Stack()
{
if (top == -1)
{
return 0;
}
top--;
return nums[top + 1];
}
float GetTop()
{
return nums[top];
}
void Push_Stack(float num)
{
if (top == 49)
return;
top++;
nums[top] = num;
}
}
class Stack_Char
{
char str[];
int top;
Stack_Char()
{
str = new char[50];
top = -1;
}
boolean CanPush(char c)
{
int temp = top;
if (c == '(')
{
while (temp != -1)
{
if (str[temp] == '(')
{
return false;
}
temp--;
}
}
temp = top;
if (c == '[')
{
while (temp != -1)
{
if (str[temp] == '[' || str[temp] == '(')
{
return false;
}
temp--;
}
}
if (c == '{')
{
while (temp != -1)
{
if (str[temp] == '{' || str[temp] == '[' || str[temp] == '(')
{
return false;
}
temp--;
}
}
return true;
}
boolean IsEmpty()
{
if (top == -1)
return true;
else
return false;
}
void Push_Stack(char ch)
{
if (top == 49)
return;
top++;
str[top] = ch;
}
char Pop_Stack()
{
if (top == -1)
return '\0';
top--;
return str[top + 1];
}
char GetTop()
{
if (top == -1)
{
System.out.print("error");
System.exit(0);
}
return str[top];
}
}
public class jisuanqi extends javax.swing.JFrame implements ActionListener
{
JTextField text = new JTextField();
JTextField text1 = new JTextField();
JButton jButton1 = new JButton();
JButton jButton2 = new JButton();
JButton jButton3 = new JButton();
JButton jButton4 = new JButton();
JButton jButton5 = new JButton();
JButton jButton6 = new JButton();
JButton jButton7 = new JButton();
JButton jButton8 = new JButton();
JButton jButton9 = new JButton();
JButton jButton10 = new JButton();
JButton jButton11 = new JButton();
JButton jButton12 = new JButton();
JButton jButton13 = new JButton();
JButton jButton14 = new JButton();
JButton jButton15 = new JButton();
JButton jButton16 = new JButton();
JButton jButton17 = new JButton();
JButton jButton18 = new JButton();
JButton jButton19 = new JButton();
JButton jButton20 = new JButton();
JButton jButton21 = new JButton();
JButton jButton22 = new JButton();
String show = "";
public jisuanqi()
{
initComponents();
}
char[] TranSmit(char str[])
{
char houzhui[] = new char[50]; // 存放後綴表達式的字元串
int i = 0, j = 0;
char c = str[i];
Stack_Char s = new Stack_Char(); // 存放運算符的棧
while (c != '=') // 對算術表達式掃描未結束時
{
if (c >= '0' && c <= '9')
{
while (c >= '0' && c <= '9')// 數字直接入棧
{
houzhui[j] = c;
j++;
i++;
c = str[i];
}
houzhui[j] = '#';// 用#隔開數字
j++;
}
switch (c) // 掃描到運算符時
{
case '+':
case '-':
case '*':
case '/':
case '(':
case '[':
case '{':
if (s.IsEmpty() == true) // 棧空,直接入棧
{
s.Push_Stack(c);
i++;
c = str[i];
break;
}
if (ComPare(s.GetTop(), c) == -1) {
s.Push_Stack(c); // 入棧
i++;
c = str[i];
break;
}
if (ComPare(s.GetTop(), c) == 1) {
houzhui[j] = s.Pop_Stack();// 出棧元素存入後綴表達式
j++;
break;
}
case ')': // 掃描到 )
while (s.GetTop() != '(') // 未掃描到 ( 時,出棧
{
houzhui[j] = s.Pop_Stack();
j++;
}
s.Pop_Stack(); // '(' 出棧
i++;
c = str[i];
break;
case ']': // 掃描到 ]
while (s.GetTop() != '[') // 未掃描到 [ 時,出棧
{
houzhui[j] = s.Pop_Stack();
j++;
}
s.Pop_Stack(); // '[' 出棧
i++;
c = str[i];
break;
case '}': // 掃描到 }
while (s.GetTop() != '{') // 未掃描到 { 時,出棧
{
houzhui[j] = s.Pop_Stack();
j++;
}
s.Pop_Stack(); // '{' 出棧
i++;
c = str[i];
break;
}
}
while (s.IsEmpty() != true)// 把剩餘的運算符直接出棧
{
houzhui[j] = s.Pop_Stack();
j++;
}
houzhui[j] = '=';// 後綴表達式後面加 =
j++;
houzhui[j] = '\0';
j++;
return houzhui;
}
float Count(char str[])
{
Stack_Float s = new Stack_Float();// 定義存放數字的棧
char c = str[0];
int i = 0;
float result = 0, temp, left, right;
while (c != '=') // 未掃描到 = 時
{
if (c >= '0' && c <= '9')// 掃描到數字
{
temp = 0;
while (c != '#')// 未讀到分隔符時
{
temp = temp * 10 + c - '0';
i++;
c = str[i];
}
s.Push_Stack(temp);// 進棧
}
switch (c)// 掃描到運算符時
{
case '+':
{
result = s.Pop_Stack() + s.Pop_Stack();// 2個數字出棧相加
s.Push_Stack(result);// 最後得數進棧
break;
}
case '-':
{
right = s.Pop_Stack();// 右操作數出棧
left = s.Pop_Stack();// 左操作數出棧
result = left - right;
s.Push_Stack(result);
break;
}
case '*':
{
result = s.Pop_Stack() * s.Pop_Stack();// 2個數字出棧相乘
s.Push_Stack(result);
break;
}
case '/':
{
right = s.Pop_Stack();// 右操作數出棧
left = s.Pop_Stack();// 左操作數出棧
result = left / right;
s.Push_Stack(result);
break;
}
}
i++;
c = str[i];
}
return result;
}
int ComPare(char a, char b) // 判斷運算符的優先順序函數
{
int s[][] = {// 棧頂元素高於算術表達式中的元素時, 返回 1,否則返回 -1
{ 1, 1, -1, -1, -1, 1, -1, 1, -1, 1 },
{ 1, 1, -1, -1, -1, 1, -1, 1, -1, 1 },
{ 1, 1, 1, 1, -1, 1, -1, 1, -1, 1 },
{ 1, 1, 1, 1, -1, 1, -1, 1, -1, 1 },
{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 },
{ 1, 1, 1, 1, -1, 1, -1, -1, -1, -1 },
{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 },
{ 1, 1, 1, 1, -1, -1, -1, -1, -1, 1 },
{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 },
{ 1, 1, 1, 1, -1, -1, -1, -1, -1, -1 } };
char x1[] = { '+', '-', '*', '/', '(', ')', '[', ']', '{', '}' };// 棧頂元素
char x2[] = { '+', '-', '*', '/', '(', ')', '[', ']', '{', '}' };// 算術表達式中的元素
int k = 0, m, n = 0;
for (m = 0; m < 10; m++) // 查找2個進行比較的運算符在表中的位置,並返回比較結果
{
for (n = 0; n < 10; n++)
{
if (x1[m] == a && x2[n] == b)
{
k = 1;
break; // 找到比較結果後,跳出循環
}
}
if (k == 1)
break;
}
return s[m][n];// 返回比較結果
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == jButton1)
{
show += "1";
text.setText(show);
}
if (e.getSource() == jButton2)
{
show += "2";
text.setText(show);
}
if (e.getSource() == jButton3)
{
show += "3";
text.setText(show);
}
if (e.getSource() == jButton4)
{
show += "4";
text.setText(show);
}
if (e.getSource() == jButton5)
{
show += "5";
text.setText(show);
}
if (e.getSource() == jButton6)
{
show += "6";
text.setText(show);
}
if (e.getSource() == jButton7)
{
show += "7";
text.setText(show);
}
if (e.getSource() == jButton8)
{
show += "8";
text.setText(show);
}
if (e.getSource() == jButton9)
{
show += "9";
text.setText(show);
}
if (e.getSource() == jButton10)
{
show += "0";
text.setText(show);
}
if (e.getSource() == jButton11)
{
show += "+";
text.setText(show);
}
if (e.getSource() == jButton12)
{
show += "-";
text.setText(show);
}
if (e.getSource() == jButton13)
{
show += "*";
text.setText(show);
}
if (e.getSource() == jButton14)
{
show += "/";
text.setText(show);
}
if (e.getSource() == jButton15)
{
show += "(";
text.setText(show);
}
if (e.getSource() == jButton16)
{
show += ")";
text.setText(show);
}
if (e.getSource() == jButton17)
{
show += "[";
text.setText(show);
}
if (e.getSource() == jButton18)
{
show += "]";
text.setText(show);
}
if (e.getSource() == jButton19)
{
show += "{";
text.setText(show);
}
if (e.getSource() == jButton20)
{
show += "}";
text.setText(show);
}
if (e.getSource() == jButton21)
{
show = "";
text.setText("");
text1.setText("");
}
if (e.getSource() == jButton22)
{
show += "=";
text.setText(show);
char str1[] = new char[50];
char str2[] = new char[50];
float result = 0;
str1 = show.toCharArray();
str2 = TranSmit(str1);
result = Count(str2);
text1.setText((new String(str2)).trim());
text.setText("" + result);
show = "";
}
}
private void initComponents()
{
text.setBounds(10, 10, 270, 30);
text1.setBounds(10, 50, 270, 30);
jButton1.setBounds(10, 90, 60, 25);
jButton2.setBounds(80, 90, 60, 25);
jButton3.setBounds(150, 90, 60, 25);
jButton4.setBounds(220, 90, 60, 25);
jButton5.setBounds(10, 120, 60, 25);
jButton6.setBounds(80, 120, 60, 25);
jButton7.setBounds(150, 120, 60, 25);
jButton8.setBounds(220, 120, 60, 25);
jButton9.setBounds(10, 150, 60, 25);
jButton10.setBounds(80, 150, 60, 25);
jButton11.setBounds(150, 150, 60, 25);
jButton12.setBounds(220, 150, 60, 25);
jButton13.setBounds(10, 180, 60, 25);
jButton14.setBounds(80, 180, 60, 25);
jButton15.setBounds(150, 180, 60, 25);
jButton16.setBounds(220, 180, 60, 25);
jButton17.setBounds(150, 210, 60, 25);
jButton18.setBounds(220, 210, 60, 25);
jButton19.setBounds(10, 210, 60, 25);
jButton20.setBounds(80, 210, 60, 25);
jButton21.setBounds(10, 240, 60, 25);
jButton22.setBounds(80, 240, 60, 25);
jButton1.setText("1");
jButton2.setText("2");
jButton3.setText("3");
jButton4.setText("4");
jButton5.setText("5");
jButton6.setText("6");
jButton7.setText("7");
jButton8.setText("8");
jButton9.setText("9");
jButton10.setText("0");
jButton11.setText("+");
jButton12.setText("-");
jButton13.setText("*");
jButton14.setText("/");
jButton15.setText("(");
jButton16.setText(")");
jButton17.setText("[");
jButton18.setText("]");
jButton19.setText("{");
jButton20.setText("}");
jButton21.setText("CE");
jButton22.setText("=");
jButton1.addActionListener(this);
jButton2.addActionListener(this);
jButton3.addActionListener(this);
jButton4.addActionListener(this);
jButton5.addActionListener(this);
jButton6.addActionListener(this);
jButton7.addActionListener(this);
jButton8.addActionListener(this);
jButton9.addActionListener(this);
jButton10.addActionListener(this);
jButton11.addActionListener(this);
jButton12.addActionListener(this);
jButton13.addActionListener(this);
jButton14.addActionListener(this);
jButton15.addActionListener(this);
jButton16.addActionListener(this);
jButton17.addActionListener(this);
jButton18.addActionListener(this);
jButton19.addActionListener(this);
jButton20.addActionListener(this);
jButton21.addActionListener(this);
jButton22.addActionListener(this);
add(text);
add(text1);
add(jButton1);
add(jButton2);
add(jButton3);
add(jButton4);
add(jButton5);
add(jButton6);
add(jButton7);
add(jButton8);
add(jButton9);
add(jButton10);
add(jButton11);
add(jButton12);
add(jButton13);
add(jButton14);
add(jButton15);
add(jButton16);
add(jButton17);
add(jButton18);
add(jButton19);
add(jButton20);
add(jButton21);
add(jButton22);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
setBounds(300, 300, 300, 300);
setVisible(true);
}
public static void main(String args[])
{
new jisuanqi();
}
}