導航:首頁 > 編程語言 > java括弧計算器

java括弧計算器

發布時間:2022-05-05 19:31:24

『壹』 使用java類描述一個計算器類 計算器具備操作數1, 操作數2 ,還具備計算的功能行為。

//給你給之前我些的代碼
//封裝兩個數
publicclassComputer{
privatedoublenum1;
privatedoublenum2;

publicComputer(){
}
publicComputer(doublenum1,doublenum2){
this.num1=num1;
this.num2=num2;
}
publicdoublegetNum1(){
returnnum1;
}
publicvoidsetNum1(doublenum1){
this.num1=num1;
}
publicdoublegetNum2(){
returnnum2;
}
publicvoidsetNum2(doublenum2){
this.num2=num2;
}
}
//封裝加法運算
publicclassSum{

publicdoublemethod(Computercom){
returncom.getNum1()+com.getNum2();
}
}
//封裝減法運算
publicclassSubtraction{
publicdoublemethod(Computercom){
returncom.getNum1()-com.getNum2();
}
}
//封裝乘法運算
publicclassProct{
publicdoublemethod(Computercom){
returncom.getNum1()*com.getNum2();
}

}
//封裝除法運算
publicclassDivide{

publicdoublemethod(Computercom){
returncom.getNum1()/com.getNum2();
}
}
//封裝運算過程
publicclassComputerFactry{
publicdoublemethod(intoption,doublenum1,doublenum2){
doublenumber=0;
Computercom=newComputer(num1,num2);
switch(option){
case1:
number=newSum().method(com);
break;
case2:
number=newSubtraction().method(com);
break;
case3:
number=newProct().method(com);
break;
case4:
number=newDivide().method(com);
break;

}
returnnumber;
}
}
//程序界面
importjava.util.Scanner;
publicclassDemo{
publicstaticvoidmain(String[]args){
doublenum1=0,num2=0;
intoption=0;
Scannersca=newScanner(System.in);
ComputerFactrycf=newComputerFactry();
System.out.println(" "+"=====歡迎使用計算器=====");
System.out.println("1,加法運算(+)");
System.out.println("2,減法運算(-)");
System.out.println("3,乘法運算(×)");
System.out.println("4,除法運算(÷)");
System.out.print("請選擇運算方法:");
option=sca.nextInt();
System.out.print("請輸入第一個數:");
num1=sca.nextDouble();
System.out.print("請輸入第二個數:");
num2=sca.nextDouble();
System.out.println(cf.method(option,num1,num2));
}
}

『貳』 java實現計算器的程序

///你運行看看,效果絕對讓你滿意!呵呵……
///////
import java.awt.*;
import java.awt.event.*;
import java.lang.*;
import javax.swing.*;
public class Counter extends Frame
{
//聲明三個面板的布局
GridLayout gl1,gl2,gl3;
Panel p0,p1,p2,p3;
JTextField tf1;
TextField tf2;
Button b0,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;
StringBuffer str;//顯示屏所顯示的字元串
double x,y;//x和y都是運算數
int z;//Z表示單擊了那一個運算符.0表示"+",1表示"-",2表示"*",3表示"/"
static double m;//記憶的數字
public Counter()
{
gl1=new GridLayout(1,4,10,0);//實例化三個面板的布局
gl2=new GridLayout(4,1,0,15);
gl3=new GridLayout(4,5,10,15);

tf1=new JTextField(27);//顯示屏
tf1.setHorizontalAlignment(JTextField.RIGHT);
tf1.setEnabled(false);
tf1.setText("0");
tf2=new TextField(10);//顯示記憶的索引值
tf2.setEditable(false);
//實例化所有按鈕、設置其前景色並注冊監聽器
b0=new Button("Backspace");
b0.setForeground(Color.red);
b0.addActionListener(new Bt());
b1=new Button("CE");
b1.setForeground(Color.red);
b1.addActionListener(new Bt());
b2=new Button("C");
b2.setForeground(Color.red);
b2.addActionListener(new Bt());
b3=new Button("MC");
b3.setForeground(Color.red);
b3.addActionListener(new Bt());
b4=new Button("MR");
b4.setForeground(Color.red);
b4.addActionListener(new Bt());
b5=new Button("MS");
b5.setForeground(Color.red);
b5.addActionListener(new Bt());
b6=new Button("M+");
b6.setForeground(Color.red);
b6.addActionListener(new Bt());
b7=new Button("7");
b7.setForeground(Color.blue);
b7.addActionListener(new Bt());
b8=new Button("8");
b8.setForeground(Color.blue);
b8.addActionListener(new Bt());
b9=new Button("9");
b9.setForeground(Color.blue);
b9.addActionListener(new Bt());
b10=new Button("/");
b10.setForeground(Color.red);
b10.addActionListener(new Bt());
b11=new Button("sqrt");
b11.setForeground(Color.blue);
b11.addActionListener(new Bt());
b12=new Button("4");
b12.setForeground(Color.blue);
b12.addActionListener(new Bt());
b13=new Button("5");
b13.setForeground(Color.blue);
b13.addActionListener(new Bt());
b14=new Button("6");
b14.setForeground(Color.blue);
b14.addActionListener(new Bt());
b15=new Button("*");
b15.setForeground(Color.red);
b15.addActionListener(new Bt());
b16=new Button("%");
b16.setForeground(Color.blue);
b16.addActionListener(new Bt());
b17=new Button("1");
b17.setForeground(Color.blue);
b17.addActionListener(new Bt());
b18=new Button("2");
b18.setForeground(Color.blue);
b18.addActionListener(new Bt());
b19=new Button("3");
b19.setForeground(Color.blue);
b19.addActionListener(new Bt());
b20=new Button("-");
b20.setForeground(Color.red);
b20.addActionListener(new Bt());
b21=new Button("1/X");
b21.setForeground(Color.blue);
b21.addActionListener(new Bt());
b22=new Button("0");
b22.setForeground(Color.blue);
b22.addActionListener(new Bt());
b23=new Button("+/-");
b23.setForeground(Color.blue);
b23.addActionListener(new Bt());
b24=new Button(".");
b24.setForeground(Color.blue);
b24.addActionListener(new Bt());
b25=new Button("+");
b25.setForeground(Color.red);
b25.addActionListener(new Bt());
b26=new Button("=");
b26.setForeground(Color.red);
b26.addActionListener(new Bt());

//實例化四個面板
p0=new Panel();
p1=new Panel();
p2=new Panel();
p3=new Panel();
//創建一個空字元串緩沖區
str=new StringBuffer();

//添加面板p0中的組件和設置其在框架中的位置和大小
p0.add(tf1);
p0.setBounds(10,25,300,40);
//添加面板p1中的組件和設置其在框架中的位置和大小
p1.setLayout(gl1);
p1.add(tf2);
p1.add(b0);
p1.add(b1);
p1.add(b2);
p1.setBounds(10,65,300,25);
//添加面板p2中的組件並設置其的框架中的位置和大小
p2.setLayout(gl2);
p2.add(b3);
p2.add(b4);
p2.add(b5);
p2.add(b6);
p2.setBounds(10,110,40,150);
//添加面板p3中的組件並設置其在框架中的位置和大小
p3.setLayout(gl3);//設置p3的布局
p3.add(b7);
p3.add(b8);
p3.add(b9);
p3.add(b10);
p3.add(b11);
p3.add(b12);
p3.add(b13);
p3.add(b14);
p3.add(b15);
p3.add(b16);
p3.add(b17);
p3.add(b18);
p3.add(b19);
p3.add(b20);
p3.add(b21);
p3.add(b22);
p3.add(b23);
p3.add(b24);
p3.add(b25);
p3.add(b26);
p3.setBounds(60,110,250,150);
//設置框架中的布局為空布局並添加4個面板
setLayout(null);
add(p0);
add(p1);
add(p2);
add(p3);
setResizable(false);//禁止調整框架的大小
//匿名類關閉窗口
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e1)
{
System.exit(0);
}
});
setBackground(Color.lightGray);
setBounds(100,100,320,280);
setVisible(true);

}
//構造監聽器
class Bt implements ActionListener
{
public void actionPerformed(ActionEvent e2)
{
try{

if(e2.getSource()==b1)//選擇"CE"清零
{
tf1.setText("0");//把顯示屏清零
str.setLength(0);//清空字元串緩沖區以准備接收新的輸入運算數
}
else if(e2.getSource()==b2)//選擇"C"清零
{
tf1.setText("0");//把顯示屏清零
str.setLength(0);
}
else if(e2.getSource()==b23)//單擊"+/-"選擇輸入的運算數是正數還是負數
{
x=Double.parseDouble(tf1.getText().trim());
tf1.setText(""+(-x));
}
else if(e2.getSource()==b25)//單擊加號按鈕獲得x的值和z的值並清空y的值
{
x=Double.parseDouble(tf1.getText().trim());
str.setLength(0);//清空緩沖區以便接收新的另一個運算數
y=0d;
z=0;
}
else if(e2.getSource()==b20)//單擊減號按鈕獲得x的值和z的值並清空y的值
{
x=Double.parseDouble(tf1.getText().trim());
str.setLength(0);
y=0d;
z=1;
}
else if(e2.getSource()==b15)//單擊乘號按鈕獲得x的值和z的值並清空y的值
{
x=Double.parseDouble(tf1.getText().trim());
str.setLength(0);
y=0d;
z=2;
}
else if(e2.getSource()==b10)//單擊除號按鈕獲得x的值和z的值並空y的值
{
x=Double.parseDouble(tf1.getText().trim());
str.setLength(0);
y=0d;
z=3;
}
else if(e2.getSource()==b26)//單擊等號按鈕輸出計算結果
{
str.setLength(0);
switch(z)
{
case 0 : tf1.setText(""+(x+y));break;
case 1 : tf1.setText(""+(x-y));break;
case 2 : tf1.setText(""+(x*y));break;
case 3 : tf1.setText(""+(x/y));break;
}
}
else if(e2.getSource()==b24)//單擊"."按鈕輸入小數
{
if(tf1.getText().trim().indexOf(".")!=-1)//判斷字元串中是否已經包含了小數點
{

}
else//如果沒數點有小
{
if(tf1.getText().trim().equals("0"))//如果初時顯示為0
{
str.setLength(0);
tf1.setText((str.append("0"+e2.getActionCommand())).toString());
}
else if(tf1.getText().trim().equals(""))//如果初時顯示為空則不做任何操作
{
}
else
{
tf1.setText(str.append(e2.getActionCommand()).toString());
}
}

y=0d;

}
else if(e2.getSource()==b11)//求平方根
{
x=Double.parseDouble(tf1.getText().trim());
tf1.setText("數字格式異常");
if(x<0)
tf1.setText("負數沒有平方根");
else
tf1.setText(""+Math.sqrt(x));
str.setLength(0);
y=0d;
}
else if(e2.getSource()==b16)//單擊了"%"按鈕
{
x=Double.parseDouble(tf1.getText().trim());
tf1.setText(""+(0.01*x));
str.setLength(0);
y=0d;
}
else if(e2.getSource()==b21)//單擊了"1/X"按鈕
{

x=Double.parseDouble(tf1.getText().trim());
if(x==0)
{

tf1.setText("除數不能為零");
}
else
{
tf1.setText(""+(1/x));
}
str.setLength(0);
y=0d;
}
else if(e2.getSource()==b3)//MC為清除內存
{
m=0d;
tf2.setText("");
str.setLength(0);
}
else if(e2.getSource()==b4)//MR為重新調用存儲的數據
{
if(tf2.getText().trim()!="")//有記憶數字
{
tf1.setText(""+m);
}
}
else if(e2.getSource()==b5)//MS為存儲顯示的數據
{

m=Double.parseDouble(tf1.getText().trim());
tf2.setText("M");
tf1.setText("0");
str.setLength(0);
}
else if(e2.getSource()==b6)//M+為將顯示的數字與已經存儲的數據相加要查看新的數字單擊MR
{
m=m+Double.parseDouble(tf1.getText().trim());
}
else//選擇的是其他的按鈕
{
if(e2.getSource()==b22)//如果選擇的是"0"這個數字鍵
{
if(tf1.getText().trim().equals("0"))//如果顯示屏顯示的為零不做操作
{

}
else
{
tf1.setText(str.append(e2.getActionCommand()).toString());
y=Double.parseDouble(tf1.getText().trim());
}
}
else if(e2.getSource()==b0)//選擇的是「BackSpace」按鈕
{
if(!tf1.getText().trim().equals("0"))//如果顯示屏顯示的不是零
{
if(str.length()!=1)
{
tf1.setText(str.delete(str.length()-1,str.length()).toString());//可能拋出字元串越界異常
}
else
{
tf1.setText("0");
str.setLength(0);
}
}
y=Double.parseDouble(tf1.getText().trim());
}
else//其他的數字鍵
{
tf1.setText(str.append(e2.getActionCommand()).toString());
y=Double.parseDouble(tf1.getText().trim());
}
}
}
catch(NumberFormatException e){
tf1.setText("數字格式異常");
}
catch( e){
tf1.setText("字元串索引越界");
}
}
}
public static void main(String args[])
{
new Counter();
}

}

『叄』 JAVA帶括弧計算器

我以前做過一個,不過不記得了,講一下思路吧:
你可以用一個棧來存放數據,再用一個棧來存放符號,然後就是解析你輸入的表達式了,遇到數字就進棧,遇到運算符的話就從數字棧中出棧兩個數字進行相應的運算......

『肆』 用Java編寫一個計算器,實現+,-,*,/,%,++,--的計算操作.不用太復雜

publicstaticvoidmain(String[]args){
intone=1;
inttwo=2;
Stringmark="--";
calc(one,mark,two);//如果為遞加或遞減的情況,請注意傳參順序
}

publicstaticvoidcalc(intone,Stringmark,inttwo){
intresult=0;
switch(mark){
case"+":
result=one+two;
break;
case"-":
result=one-two;
break;
case"*":
result=one*two;
break;
case"/":
result=one/two;
break;
case"%":
result=one%two;
break;
case"++":
result=++one;
break;
case"--":
result=--one;
break;
default:
break;
}
System.out.println(result);
}

『伍』 怎麼用java做一個帶括弧的計算器

importjava.awt.*;
importjava.awt.event.*;
publicclassMyCalculator{
privateFramef;
privateTextFieldtf=newTextField(30);
privatelongresult;
privatebooleanappend=false;
privatecharoperator='=';
privateButton[]btn=newButton[15];

publicMyCalculator(){
initComponent();
}

privatevoidinitComponent(){
f=newFrame("MyCalculatorV1.0");
f.setLayout(newBorderLayout());//TheframeusesBorderLayout
f.addWindowListener(newWindowAdapter(){
publicvoidwindowClosing(WindowEventevt){
System.exit(0);
}
});

PanelcenterPanel=newPanel();
centerPanel.setLayout(newGridLayout(5,3));//ThepanelusesGridLayout

NumberListenernl=newNumberListener();
OperatorListenerol=newOperatorListener();

btn[10]=newButton("+");
btn[11]=newButton("-");
btn[12]=newButton("*");
btn[13]=newButton("/");
btn[14]=newButton("=");

for(inti=0;i<=9;i++){
btn[i]=newButton(String.valueOf(i));
centerPanel.add(btn[i]);
btn[i].addActionListener(nl);
if(i%2==1){
centerPanel.add(btn[(i+19)/2]);
btn[(i+19)/2].addActionListener(ol);
}
}
f.add(centerPanel,BorderLayout.CENTER);

PanelnorthPanel=newPanel();

tf.setEditable(false);
northPanel.add(tf);
f.add(northPanel,BorderLayout.NORTH);
}
publicvoidgo(){
f.pack();
f.setVisible(true);
}

publicstaticvoidmain(String[]args){
newMyCalculator().go();
}

/**
*採用成員內部類方式,實現監聽器介面,方便訪問主類內類內部成員。
*此類負責數字按鈕Action事件監聽和處理
*/
{
publicvoidactionPerformed(ActionEvente){
if(!append){
tf.setText("");
append=true;
}
Strings=tf.getText();
s+=e.getActionCommand();
tf.setText(s);
if(!btn[10].isEnabled()){
for(inti=10;i<=14;i++)btn[i].setEnabled(true);
}
}
}

/**
*成員內部類,負責操作符按鈕的事件處理
*/
{
publicvoidactionPerformed(ActionEvente){
if(!append)return;
for(inti=10;i<=14;i++)btn[i].setEnabled(false);
Strings=tf.getText();
longnum=Long.parseLong(s);//getthenumberoftextfield
append=false;//setappend
switch(operator){
case'+':result+=num;break;
case'-':result-=num;break;
case'*':result*=num;break;
case'/':{
if(num==0)result=0;
elseresult/=num;
break;
}
case'=':result=num;break;
}
tf.setText(String.valueOf(result));
//
Stringop=e.getActionCommand();
operator=op.charAt(0);//setoperator
}
}
}

『陸』 java實現復雜計算器

importjava.util.Scanner;

importjavax.script.ScriptEngine;
importjavax.script.ScriptEngineManager;
importjavax.script.ScriptException;

publicclassKyo
{
publicstaticvoidmain(String[]args)
{
ScriptEngineManagersem=newScriptEngineManager();
ScriptEnginese=sem.getEngineByName("js");
Scannerscan=newScanner(System.in);
while(true)
{
System.out.println("輸入一個式子:");
Stringjsonstr=scan.nextLine().trim();
try
{
doubled=Double.parseDouble(se.eval("("+jsonstr+")").toString());
System.out.printf("%s=%.1f%n",jsonstr,d);
}
catch(ScriptExceptione)
{
System.err.println("輸入的式子不合法,退出程序");
scan.close();
break;
}
}
}
}

『柒』 java如何在計算器中加入小括弧功能

這個不就看你的程序怎麼寫了嗎?你可以把用戶輸入的先保存下來,用戶按等於的時候,你的程序區解析你保存下來的東西,不就等於加入了小括弧了,怎麼解析就看你要什麼需求了,祝你成功

『捌』 求簡單計算器JAVA編程

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Calculator extends JFrame {

private Container container;

private GridBagLayout layout;

private GridBagConstraints constraints;

private JTextField displayField;// 計算結果顯示區

private String lastCommand;// 保存+,-,*,/,=命令

private double result;// 保存計算結果

private boolean start;// 判斷是否為數字的開始

public Calculator() {

super("Calculator");
container = getContentPane();
layout = new GridBagLayout();
container.setLayout(layout);
constraints = new GridBagConstraints();
start = true;
result = 0;
lastCommand = "=";
displayField = new JTextField(20);
displayField.setHorizontalAlignment(JTextField.RIGHT);
constraints.gridx = 0;
constraints.gridy = 0;
constraints.gridwidth = 4;
constraints.gridheight = 1;
constraints.fill = GridBagConstraints.BOTH;
constraints.weightx = 100;
constraints.weighty = 100;
layout.setConstraints(displayField, constraints);
container.add(displayField);
ActionListener insert = new InsertAction();
ActionListener command = new CommandAction();
// addButton("Backspace", 0, 1, 2, 1, insert);
// addButton("CE", 2, 1, 1, 1, insert);
// addButton("C", 3, 1, 1, 1, insert);
addButton("7", 0, 2, 1, 1, insert);
addButton("8", 1, 2, 1, 1, insert);
addButton("9", 2, 2, 1, 1, insert);
addButton("/", 3, 2, 1, 1, command);
addButton("4", 0, 3, 1, 1, insert);
addButton("5", 1, 3, 1, 1, insert);
addButton("6", 2, 3, 1, 1, insert);
addButton("*", 3, 3, 1, 1, command);
addButton("1", 0, 4, 1, 1, insert);
addButton("2", 1, 4, 1, 1, insert);
addButton("3", 2, 4, 1, 1, insert);
addButton("-", 3, 4, 1, 1, command);
addButton("0", 0, 5, 1, 1, insert);
// addButton("+/-", 1, 5, 1, 1, insert);// 只顯示"-"號,"+"沒有實用價值
addButton(".", 2, 5, 1, 1, insert);
addButton("+", 3, 5, 1, 1, command);
addButton("=", 0, 6, 4, 1, command);
this.setResizable(false);
setSize(180, 200);
setVisible(true);

}

private void addButton(String label, int row, int column, int with,
int height, ActionListener listener) {

JButton button = new JButton(label);
constraints.gridx = row;
constraints.gridy = column;
constraints.gridwidth = with;
constraints.gridheight = height;
constraints.fill = GridBagConstraints.BOTH;
button.addActionListener(listener);
layout.setConstraints(button, constraints);
container.add(button);
}

private class InsertAction implements ActionListener {

public void actionPerformed(ActionEvent event) {

String input = event.getActionCommand();
if (start) {
displayField.setText("");
start = false;
if (input.equals("+/-"))
displayField.setText(displayField.getText() + "-");
}

if (!input.equals("+/-")) {
if (input.equals("Backspace")) {
String str = displayField.getText();
if (str.length() > 0)
displayField
.setText(str.substring(0, str.length() - 1));
} else if (input.equals("CE") || input.equals("C")) {
displayField.setText("0");
start = true;
} else
displayField.setText(displayField.getText() + input);
}
}
}

private class CommandAction implements ActionListener {

public void actionPerformed(ActionEvent evt) {
String command = evt.getActionCommand();
if (start) {
lastCommand = command;
} else {
calculate(Double.parseDouble(displayField.getText()));
lastCommand = command;
start = true;
}
}
}

public void calculate(double x) {
if (lastCommand.equals("+"))
result += x;
else if (lastCommand.equals("-"))
result -= x;
else if (lastCommand.equals("*"))
result *= x;
else if (lastCommand.equals("/"))
result /= x;
else if (lastCommand.equals("="))
result = x;
displayField.setText("" + result);
}

public static void main(String[] args) {
Calculator calculator = new Calculator();
calculator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

}

『玖』 用java設計一個計算器 1.可以沒有界面,但要有輸入和輸出 2.整數,小數,加減乘除,求余,括弧

package com.electricauto.work.controller;
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;

/**
* 一個計算器,與Windows附件自帶計算器的標准版功能、界面相仿。 但還不支持鍵盤操作。
*/
public class jisuanqi extends JFrame implements ActionListener {
/** 計算器上的鍵的顯示名字 */
private final String[] KEYS = { "7", "8", "9", "/", "sqrt", "4", "5", "6",
"*", "%", "1", "2", "3", "-", "1/x", "0", "+/-", ".", "+", "=" };
/** 計算器上的功能鍵的顯示名字 */
private final String[] COMMAND = { "Backspace", "CE", "C" };
/** 計算器左邊的M的顯示名字 */
private final String[] M = { " ", "MC", "MR", "MS", "M+" };
/** 計算器上鍵的按鈕 */
private JButton keys[] = new JButton[KEYS.length];
/** 計算器上的功能鍵的按鈕 */
private JButton commands[] = new JButton[COMMAND.length];
/** 計算器左邊的M的按鈕 */
private JButton m[] = new JButton[M.length];
/** 計算結果文本框 */
private JTextField resultText = new JTextField("0");

// 標志用戶按的是否是整個表達式的第一個數字,或者是運算符後的第一個數字
private boolean firstDigit = true;
// 計算的中間結果。
private double resultNum = 0.0;
// 當前運算的運算符
private String operator = "=";
// 操作是否合法
private boolean operateValidFlag = true;

/**
* 構造函數
*/
public jisuanqi() {
super();
// 初始化計算器
init();
// 設置計算器的背景顏色
this.setBackground(Color.LIGHT_GRAY);
this.setTitle("計算器");
// 在屏幕(500, 300)坐標處顯示計算器
this.setLocation(500, 300);
// 不許修改計算器的大小
this.setResizable(false);
// 使計算器中各組件大小合適
this.pack();
}

/**
* 初始化計算器
*/
private void init() {
// 文本框中的內容採用右對齊方式
resultText.setHorizontalAlignment(JTextField.RIGHT);
// 不允許修改結果文本框
resultText.setEditable(false);
// 設置文本框背景顏色為白色
resultText.setBackground(Color.white);

// 初始化計算器上鍵的按鈕,將鍵放在一個畫板內
JPanel calckeysPanel = new JPanel();
// 用網格布局器,4行,5列的網格,網格之間的水平方向間隔為3個象素,垂直方向間隔為3個象素
calckeysPanel.setLayout(new GridLayout(4, 5, 3, 3));
for (int i = 0; i < KEYS.length; i++) {
keys[i] = new JButton(KEYS[i]);
calckeysPanel.add(keys[i]);
keys[i].setForeground(Color.blue);
}
// 運算符鍵用紅色標示,其他鍵用藍色表示
keys[3].setForeground(Color.red);
keys[8].setForeground(Color.red);
keys[13].setForeground(Color.red);
keys[18].setForeground(Color.red);
keys[19].setForeground(Color.red);

// 初始化功能鍵,都用紅色標示。將功能鍵放在一個畫板內
JPanel commandsPanel = new JPanel();
// 用網格布局器,1行,3列的網格,網格之間的水平方向間隔為3個象素,垂直方向間隔為3個象素
commandsPanel.setLayout(new GridLayout(1, 3, 3, 3));
for (int i = 0; i < COMMAND.length; i++) {
commands[i] = new JButton(COMMAND[i]);
commandsPanel.add(commands[i]);
commands[i].setForeground(Color.red);
}

// 初始化M鍵,用紅色標示,將M鍵放在一個畫板內
JPanel calmsPanel = new JPanel();
// 用網格布局管理器,5行,1列的網格,網格之間的水平方向間隔為3個象素,垂直方向間隔為3個象素
calmsPanel.setLayout(new GridLayout(5, 1, 3, 3));
for (int i = 0; i < M.length; i++) {
m[i] = new JButton(M[i]);
calmsPanel.add(m[i]);
m[i].setForeground(Color.red);
}

// 下面進行計算器的整體布局,將calckeys和command畫板放在計算器的中部,
// 將文本框放在北部,將calms畫板放在計算器的西部。

// 新建一個大的畫板,將上面建立的command和calckeys畫板放在該畫板內
JPanel panel1 = new JPanel();
// 畫板採用邊界布局管理器,畫板里組件之間的水平和垂直方向上間隔都為3象素
panel1.setLayout(new BorderLayout(3, 3));
panel1.add("North", commandsPanel);
panel1.add("West", calckeysPanel);

// 建立一個畫板放文本框
JPanel top = new JPanel();
top.setLayout(new BorderLayout());
top.add("Center", resultText);

// 整體布局
getContentPane().setLayout(new BorderLayout(3, 5));
getContentPane().add("North", top);
getContentPane().add("Center", panel1);
getContentPane().add("West", calmsPanel);
// 為各按鈕添加事件偵聽器
// 都使用同一個事件偵聽器,即本對象。本類的聲明中有implements ActionListener
for (int i = 0; i < KEYS.length; i++) {
keys[i].addActionListener(this);
}
for (int i = 0; i < COMMAND.length; i++) {
commands[i].addActionListener(this);
}
for (int i = 0; i < M.length; i++) {
m[i].addActionListener(this);
}
}

/**
* 處理事件
*/
public void actionPerformed(ActionEvent e) {
// 獲取事件源的標簽
String label = e.getActionCommand();
if (label.equals(COMMAND[0])) {
// 用戶按了"Backspace"鍵
handleBackspace();
} else if (label.equals(COMMAND[1])) {
// 用戶按了"CE"鍵
resultText.setText("0");
} else if (label.equals(COMMAND[2])) {
// 用戶按了"C"鍵
handleC();
} else if ("0123456789.".indexOf(label) >= 0) {
// 用戶按了數字鍵或者小數點鍵
handleNumber(label);
// handlezero(zero);
} else {
// 用戶按了運算符鍵
handleOperator(label);
}
}

/**
* 處理Backspace鍵被按下的事件
*/
private void handleBackspace() {
String text = resultText.getText();
int i = text.length();
if (i > 0) {
// 退格,將文本最後一個字元去掉
text = text.substring(0, i - 1);
if (text.length() == 0) {
// 如果文本沒有了內容,則初始化計算器的各種值
resultText.setText("0");
firstDigit = true;
operator = "=";
} else {
// 顯示新的文本
resultText.setText(text);
}
}
}

/**
* 處理數字鍵被按下的事件
*
* @param key
*/
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 = "=";
}

/**
* 處理運算符鍵被按下的事件
*
* @param key
*/
private void handleOperator(String key) {
if (operator.equals("/")) {
// 除法運算
// 如果當前結果文本框中的值等於0
if (getNumberFromText() == 0.0) {
// 操作不合法
operateValidFlag = false;
resultText.setText("除數不能為零");
} else {
resultNum /= getNumberFromText();
}
} else if (operator.equals("1/x")) {
// 倒數運算
if (resultNum == 0.0) {
// 操作不合法
operateValidFlag = false;
resultText.setText("零沒有倒數");
} else {
resultNum = 1 / resultNum;
}
} else if (operator.equals("+")) {
// 加法運算
resultNum += getNumberFromText();
} else if (operator.equals("-")) {
// 減法運算
resultNum -= getNumberFromText();
} else if (operator.equals("*")) {
// 乘法運算
resultNum *= getNumberFromText();
} else if (operator.equals("sqrt")) {
// 平方根運算
resultNum = Math.sqrt(resultNum);
} else if (operator.equals("%")) {
// 百分號運算,除以100
resultNum = resultNum / 100;
} else if (operator.equals("+/-")) {
// 正數負數運算
resultNum = resultNum * (-1);
} 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;//這個地方太tm巧妙了想好幾天, 先進行上一次操作,再將本次操作(最後一次操作)賦給操作,所以每次操作前都先進行上一次操作,默認操作為"=" 挺nb
operateValidFlag = true;
}

/**
* 從結果文本框中獲取數字
*
* @return
*/
private double getNumberFromText() {
double result = 0;
try {
result = Double.valueOf(resultText.getText()).doubleValue(); //顯示文字後不會蹦出
} catch (NumberFormatException e) {
}
return result;
}

public static void main(String args[]) {
jisuanqi calculator1 = new jisuanqi();
calculator1.setVisible(true);
calculator1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
========================================================
代碼比較多,放在任何一個項目里都行,新建一個叫做 jisuanqi 的java文件,粘貼進去就行,會有一個錯誤是包位置的選擇,點擊錯誤選擇正確的包位置就可以了, 無錯誤後執行文件最下面的main函數,就會出現計算器。有不懂的可以繼續問,望採納~!

閱讀全文

與java括弧計算器相關的資料

熱點內容
安卓qq郵箱格式怎麼寫 瀏覽:429
如何電信租用伺服器嗎 瀏覽:188
編程中計算根號的思維 瀏覽:181
可愛的程序員16集背景音樂 瀏覽:446
軟體代碼內容轉換加密 瀏覽:795
什麼app看電視不要錢的 瀏覽:16
烏班圖怎麼安裝c語言編譯器 瀏覽:278
plc通訊塊編程 瀏覽:923
我的世界伺服器怎麼清地皮 瀏覽:421
ftp伺服器如何批量改名 瀏覽:314
網易我的世界伺服器成員如何傳送 瀏覽:268
公司雲伺服器遠程訪問 瀏覽:633
法哲學pdf 瀏覽:637
清大閱讀app是什麼 瀏覽:447
怎麼用qq瀏覽器整體解壓文件 瀏覽:585
肺組織壓縮15 瀏覽:270
安卓手機為什麼換電話卡沒反應 瀏覽:797
諸子集成pdf 瀏覽:339
php注冊框代碼 瀏覽:717
手機加密好還是不加好好 瀏覽:815