A. 用java編寫的計算器
package main;
import java.awt.Button;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.math.BigDecimal;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Calculator extends JFrame implements ActionListener {
static Panel pan = new Panel();
static JTextField textField = new JTextField("0");
static Button b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, bp, ba, bs, bm, bd,
be, bc, bt, bf, bh;
private StringBuffer temp = new StringBuffer("");
private String optValue = "0";
private String optType="";
private boolean isChoiseOptType=true;
public void init() {
b0 = new Button("0");
b0.addActionListener(this);
b1 = new Button("1");
b1.addActionListener(this);
b2 = new Button("2");
b2.addActionListener(this);
b3 = new Button("3");
b3.addActionListener(this);
b4 = new Button("4");
b4.addActionListener(this);
b5 = new Button("5");
b5.addActionListener(this);
b6 = new Button("6");
b6.addActionListener(this);
b7 = new Button("7");
b7.addActionListener(this);
b8 = new Button("8");
b8.addActionListener(this);
b9 = new Button("9");
b9.addActionListener(this);
bp = new Button(".");
bp.addActionListener(this);
ba = new Button("+");
ba.addActionListener(this);
bs = new Button("-");
bs.addActionListener(this);
bm = new Button("*");
bm.addActionListener(this);
bd = new Button("/");
bd.addActionListener(this);
be = new Button("=");
be.addActionListener(this);
bc = new Button("c");
bc.addActionListener(this);
bt = new Button("退格");
bt.addActionListener(this);
bf = new Button("1/x");
bf.addActionListener(this);
bh = new Button("+/-");
bh.addActionListener(this);
this.setTitle("計算機");
this.setLayout(null);
this.setSize(260, 300);
this.setResizable(false);
GridLayout grid = new GridLayout(4, 5);
pan.setLayout(grid);
pan.setBounds(20, 60, 150, 120);
textField.setBounds(20, 35, 150, 20);
textField.setBackground(Color.cyan);
textField.setHorizontalAlignment(textField.RIGHT);
textField.setEditable(false);
pan.add(b1);
pan.add(b2);
pan.add(b3);
pan.add(ba);
pan.add(bc);
pan.add(b4);
pan.add(b5);
pan.add(b6);
pan.add(bs);
pan.add(bt);
pan.add(b7);
pan.add(b8);
pan.add(b9);
pan.add(bm);
pan.add(bf);
pan.add(b0);
pan.add(bh);
pan.add(bp);
pan.add(bd);
pan.add(be);
this.add(textField);
this.add(pan);
}
public static void main(String[] args) {
Calculator frm = new Calculator();
frm.init();
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm.setVisible(true);
}
@SuppressWarnings("static-access")
@Override
public void actionPerformed(ActionEvent e) {
String value="0";
if (e.getSource().equals(b0)) {
this.temp.append(b0.getLabel());
this.textField.setText(this.temp.toString());
isChoiseOptType=false;
} else if (e.getSource().equals(b1)) {
this.temp.append(b1.getLabel());
this.textField.setText(this.temp.toString());
isChoiseOptType=false;
} else if (e.getSource().equals(b2)) {
this.temp.append(b2.getLabel());
this.textField.setText(this.temp.toString());
isChoiseOptType=false;
} else if (e.getSource().equals(b3)) {
this.temp.append(b3.getLabel());
this.textField.setText(this.temp.toString());
isChoiseOptType=false;
} else if (e.getSource().equals(b4)) {
this.temp.append(b4.getLabel());
this.textField.setText(this.temp.toString());
isChoiseOptType=false;
} else if (e.getSource().equals(b5)) {
this.temp.append(b5.getLabel());
this.textField.setText(this.temp.toString());
isChoiseOptType=false;
} else if (e.getSource().equals(b6)) {
this.temp.append(b6.getLabel());
this.textField.setText(this.temp.toString());
isChoiseOptType=false;
} else if (e.getSource().equals(b7)) {
this.temp.append(b7.getLabel());
this.textField.setText(this.temp.toString());
isChoiseOptType=false;
} else if (e.getSource().equals(b8)) {
this.temp.append(b8.getLabel());
this.textField.setText(this.temp.toString());
isChoiseOptType=false;
} else if (e.getSource().equals(b9)) {
this.temp.append(b9.getLabel());
this.textField.setText(this.temp.toString());
isChoiseOptType=false;
} else if (e.getSource().equals(bp)) {
if(this.temp.length()<=0)
this.temp.append("0");
this.temp.append(bp.getLabel());
this.textField.setText(this.temp.toString());
isChoiseOptType=false;
} else if (e.getSource().equals(ba)) {
if(!isChoiseOptType){
value=this.textField.getText();
if(value.lastIndexOf(".")==value.length()-1){
value=value.substring(0,value.length()-1);
}
this.optValue=value;
this.temp=new StringBuffer("");
}
this.optType=ba.getLabel();
isChoiseOptType=true;
} else if (e.getSource().equals(bs)) {
if(!isChoiseOptType){
value=this.textField.getText();
if(value.lastIndexOf(".")==value.length()-1){
value=value.substring(0,value.length()-1);
}
this.optValue=value;
this.temp=new StringBuffer("");
}
this.optType=bs.getLabel();
isChoiseOptType=true;
} else if (e.getSource().equals(bm)) {
if(!isChoiseOptType){
value=this.textField.getText();
if(value.lastIndexOf(".")==value.length()-1){
value=value.substring(0,value.length()-1);
}
this.optValue=value;
this.temp=new StringBuffer("");
}
this.optType=bm.getLabel();
isChoiseOptType=true;
} else if (e.getSource().equals(bd)) {
if(!isChoiseOptType){
value=this.textField.getText();
if(value.lastIndexOf(".")==value.length()-1){
value=value.substring(0,value.length()-1);
}
this.optValue=value;
this.temp=new StringBuffer("");
}
this.optType=bd.getLabel();
isChoiseOptType=true;
}else if (e.getSource().equals(be)) {
if(!this.optType.equals("")){
BigDecimal opt1=new BigDecimal(this.optValue);
value=this.textField.getText();
if(value.lastIndexOf(".")==value.length()-1){
value=value.substring(0,value.length()-1);
}
BigDecimal opt2=new BigDecimal(value);
BigDecimal result=new BigDecimal(0);
if(this.optType.equals("+")){
result=opt1.add(opt2);
}else if(this.optType.equals("-")){
result=opt1.subtract(opt2);
}else if(this.optType.equals("*")){
result=opt1.multiply(opt2);
}else if(this.optType.equals("/")){
result=opt1.divide(opt2);
}else if(this.optType.equals("%")){
result=opt1.remainder(opt2);
}
this.textField.setText(result.toString());
this.temp=new StringBuffer("");
isChoiseOptType=false;
this.optValue="0";
}
} else if (e.getSource().equals(bc)) {
this.temp=new StringBuffer();
this.textField.setText("0");
} else if (e.getSource().equals(bt)) {
value=this.textField.getText();
value=value.substring(0,value.length()-1);
if(value.indexOf("-")>=0 && value.length()<=1){
value="0";
this.temp=new StringBuffer("");
}else{
this.temp=new StringBuffer(value);
}
this.textField.setText(value);
}else if (e.getSource().equals(bh)) {
value=this.textField.getText();
if(value.indexOf("-")==0){
value=value.substring(1,value.length());
}else{
value="-"+value;
}
this.temp=new StringBuffer(value);
this.textField.setText(value);
} else if (e.getSource().equals(bf)) {
this.optValue=this.textField.getText();
if(value.lastIndexOf(".")==value.length()-1){
this.optValue=this.optValue.substring(0,this.optValue.length()-1);
}
Integer opt1=new Integer(this.optValue);
if(!opt1.toString().equals("0")){
this.textField.setText(1.0/opt1.intValue()+"");
System.out.println(1/opt1.intValue()+"");
}else{
this.textField.setText("0");
}
this.temp=new StringBuffer("");
this.optType="";
this.optValue="0";
}
}
}
B. 怎麼用java做個簡單的計算器
/*
* @(#)JCalculator.java 1.00 06/17/2015
*/
importjava.awt.*;
importjava.awt.event.*;
importjavax.swing.*;
/**
* A simple calculator program.
*<p>I saw this program in a QQ group, and help a friend correct it.</p>
*
*@authorSingyuenYip
*@version1.00 12/29/2009
*@seeJFrame
*@seeActionListener
*/
{
/**
* Serial Version UID
*/
= -169068472193786457L;
/**
* This class help close the Window.
*@authorSingyuenYip
*
*/
{
publicvoidwindowClosing(WindowEvent we) {
System.exit(0);
}
}
inti;
// Strings for Digit & Operator buttons.
privatefinalString[]str= {"7","8","9","/","4","5","6","*","1",
"2","3","-",".","0","=","+"};
// Build buttons.
JButton[]buttons=newJButton[str.length];
// For cancel or reset.
JButtonreset=newJButton("CE");
// Build the text field to show the result.
JTextFielddisplay=newJTextField("0");
/**
* Constructor without parameters.
*/
publicJCalculator() {
super("Calculator");
// Add a panel.
JPanel panel1 =newJPanel(newGridLayout(4, 4));
// panel1.setLayout(new GridLayout(4,4));
for(i= 0;i<str.length;i++) {
buttons[i] =newJButton(str[i]);
panel1.add(buttons[i]);
}
JPanel panel2 =newJPanel(newBorderLayout());
// panel2.setLayout(new BorderLayout());
panel2.add("Center",display);
panel2.add("East",reset);
// JPanel panel3 = new Panel();
getContentPane().setLayout(newBorderLayout());
getContentPane().add("North", panel2);
getContentPane().add("Center", panel1);
// Add action listener for each digit & operator button.
for(i= 0;i<str.length;i++)
buttons[i].addActionListener(this);
// Add listener for "reset" button.
reset.addActionListener(this);
// Add listener for "display" button.
display.addActionListener(this);
// The "close" button "X".
addWindowListener(newWindowCloser());
// Initialize the window size.
setSize(800, 800);
// Show the window.
// show(); Using show() while JDK version is below 1.5.
setVisible(true);
// Fit the certain size.
pack();
}
publicvoidactionPerformed(ActionEvent e) {
Object target = e.getSource();
String label = e.getActionCommand();
if(target ==reset)
handleReset();
elseif("0123456789.".indexOf(label) > 0)
handleNumber(label);
else
handleOperator(label);
}
// Is the first digit pressed?
booleanisFirstDigit=true;
/**
* Number handling.
*@paramkey the key of the button.
*/
publicvoidhandleNumber(String key) {
if(isFirstDigit)
display.setText(key);
elseif((key.equals(".")) && (display.getText().indexOf(".") < 0))
display.setText(display.getText() +".");
elseif(!key.equals("."))
display.setText(display.getText() + key);
isFirstDigit=false;
}
/**
* Reset the calculator.
*/
publicvoidhandleReset() {
display.setText("0");
isFirstDigit=true;
operator="=";
}
doublenumber= 0.0;
Stringoperator="=";
/**
* Handling the operation.
*@paramkey pressed operator's key.
*/
publicvoidhandleOperator(String key) {
if(operator.equals("+"))
number+= Double.valueOf(display.getText());
elseif(operator.equals("-"))
number-= Double.valueOf(display.getText());
elseif(operator.equals("*"))
number*= Double.valueOf(display.getText());
elseif(operator.equals("/"))
number/= Double.valueOf(display.getText());
elseif(operator.equals("="))
number= Double.valueOf(display.getText());
display.setText(String.valueOf(number));
operator= key;
isFirstDigit=true;
}
publicstaticvoidmain(String[] args) {
newJCalculator();
}
}
運行界面:
C. 怎麼用JAVA編程編寫一個計算器
打開IED:打開自己java編程的軟體,採用的是eclipse軟體。
建立java工程。
編寫類。
D. 用JAVA編寫一個簡單的計算器,要求如下
以下是上圖計算器的代碼:
packageComputer;
importjava.awt.BorderLayout;
importjava.awt.Color;
importjava.awt.Container;
importjava.awt.Font;
importjava.awt.GridLayout;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjava.util.Stack;
importjavax.swing.JApplet;
importjavax.swing.JButton;
importjavax.swing.JFrame;
importjavax.swing.JPanel;
importjavax.swing.JTextField;
{
/**
*
*/
=1L;
privateJTextFieldtextField=newJTextField("請輸入");
Stringoperator="";//操作
Stringinput="";//輸入的式子
booleanflag=true;
//booleanflag1=true;
//booleanflag2=true;
publicvoidinit()//覆寫Applet里邊的init方法
{
ContainerC=getContentPane();
JButtonb[]=newJButton[16];
JPanelpanel=newJPanel();
C.add(textField,BorderLayout.NORTH);
C.add(panel,BorderLayout.CENTER);
panel.setLayout(newGridLayout(4,4,5,5));
Stringname[]={"7","8","9","+","4","5","6","-","1","2","3","*","0","C","=","/"};//設置按鈕
for(inti=0;i<16;i++)//添加按鈕
{
b[i]=newJButton(name[i]);
b[i].setBackground(newColor(192,192,192));
b[i].setForeground(Color.BLUE);//數字鍵設置為藍顏色
if(i%4==3)
b[i].setForeground(Color.RED);
b[i].setFont(newFont("宋體",Font.PLAIN,16));//設置字體格式
panel.add(b[i]);
b[i].addActionListener(this);
}
b[13].setForeground(Color.RED);//非數字鍵,即運算鍵設置為紅顏色
b[13].setForeground(Color.RED);
}
publicvoidactionPerformed(ActionEvente)
{
intcnt=0;
StringactionCommand=e.getActionCommand();
if(actionCommand.equals("+")||actionCommand.equals("-")||actionCommand.equals("*")||actionCommand.equals("/"))
input+=""+actionCommand+"";//設置輸入,把輸入的樣式改成需要的樣子
elseif(actionCommand.equals("C"))
input="";
elseif(actionCommand.equals("="))//當監聽到等號時,則處理input
{
input+="="+compute(input);
textField.setText(input);
input="";
cnt=1;
}
else
input+=actionCommand;//數字為了避免多位數的輸入不需要加空格
if(cnt==0)
textField.setText(input);
}
privateStringcompute(Stringinput)//即1237的樣例
{
Stringstr[];
str=input.split("");
Stack<Double>s=newStack<Double>();
doublem=Double.parseDouble(str[0]);
s.push(m);
for(inti=1;i<str.length;i++)
{
if(i%2==1)
{
if(str[i].compareTo("+")==0)
{
doublehelp=Double.parseDouble(str[i+1]);
s.push(help);
}
if(str[i].compareTo("-")==0)
{
doublehelp=Double.parseDouble(str[i+1]);
s.push(-help);
}
if(str[i].compareTo("*")==0)
{
doublehelp=Double.parseDouble(str[i+1]);
doubleans=s.peek();//取出棧頂元素
s.pop();//消棧
ans*=help;
s.push(ans);
}
if(str[i].compareTo("/")==0)
{
doublehelp=Double.parseDouble(str[i+1]);
doubleans=s.peek();
s.pop();
ans/=help;
s.push(ans);
}
}
}
doubleans=0d;
while(!s.isEmpty())
{
ans+=s.peek();
s.pop();
}
Stringresult=String.valueOf(ans);
returnresult;
}
publicstaticvoidmain(Stringargs[])
{
JFrameframe=newJFrame("Count");
Countapplet=newCount();
frame.getContentPane().add(applet,BorderLayout.CENTER);
applet.init();//applet的init方法
applet.start();//線程開始
frame.setSize(350,400);//設置窗口大小
frame.setVisible(true);//設置窗口可見
}
}
E. 用Java做一個簡單的計算器
窗體
package Calc;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
*
* 計算器程序
*
*/
public class CalcFrame extends JFrame {
JButton[] buttons = new JButton[16];// 16個按鈕
StringBuffer sb = null;//
JTextField text1 = null;// 計算器結果顯示框
String no1 = null;
String sign = null;// 表示+-*/符號
String[] s = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "-",
"*", "/", "=", "C" };// 面板上的字元
public CalcFrame() {
setTitle("計算器");
setResizable(false);
setBounds(200, 200, 300, 350);
setLayout(null);
sb = new StringBuffer();
text1 = new JTextField();
text1.setBounds(10, 10, 250, 30);// 設置位置
text1.setFont(new Font("Arial", Font.PLAIN, 20));// 設置字體
text1.setForeground(Color.RED);// 設置顏色
add(text1);
for (int i = 0; i < s.length; i++) {
buttons[i] = new JButton(s[i]);
buttons[i].setFont(new Font("Serif", Font.BOLD, 18));
add(buttons[i]);
}// 生成面板上的按鈕.
buttons[0].setBounds(10, 50, 50, 40);
buttons[0].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sb.append(0);
text1.setText(sb.toString());
}
});
buttons[1].setBounds(70, 50, 50, 40);
buttons[1].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sb.append(1);
text1.setText(sb.toString());
}
});
buttons[2].setBounds(130, 50, 50, 40);
buttons[2].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sb.append(2);
text1.setText(sb.toString());
}
});
buttons[3].setBounds(190, 50, 50, 40);
buttons[3].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sb.append(3);
text1.setText(sb.toString());
}
});
buttons[4].setBounds(10, 100, 50, 40);
buttons[4].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sb.append(4);
text1.setText(sb.toString());
}
});
buttons[5].setBounds(70, 100, 50, 40);
buttons[5].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sb.append(5);
text1.setText(sb.toString());
}
});
buttons[6].setBounds(130, 100, 50, 40);
buttons[6].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sb.append(6);
text1.setText(sb.toString());
}
});
buttons[7].setBounds(190, 100, 50, 40);
buttons[7].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sb.append(7);
text1.setText(sb.toString());
}
});
buttons[8].setBounds(10, 150, 50, 40);
buttons[8].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sb.append(8);
text1.setText(sb.toString());
}
});
buttons[9].setBounds(70, 150, 50, 40);
buttons[9].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sb.append(9);
text1.setText(sb.toString());
}
});
buttons[10].setBounds(130, 150, 50, 40);
buttons[10].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sign = "+";
no1 = text1.getText();
sb.delete(0, sb.capacity());
}
});
buttons[11].setBounds(190, 150, 50, 40);
buttons[11].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sign = "-";
no1 = text1.getText();
sb.delete(0, sb.capacity());
}
});
buttons[12].setBounds(10, 200, 50, 40);
buttons[12].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sign = "*";
no1 = text1.getText();
sb.delete(0, sb.capacity());
}
});
buttons[13].setBounds(70, 200, 50, 40);
buttons[13].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sign = "/";
no1 = text1.getText();
sb.delete(0, sb.capacity());
}
});
buttons[14].setForeground(Color.RED);
buttons[14].setBounds(130, 200, 50, 40);
buttons[14].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int sum = 0;//最終結果
if (sign.equals("+")) {
int no2 = Integer.parseInt(no1);//取得前一個數
int no3 = Integer.parseInt(text1.getText());//取得現在的數
sum = no2 + no3;//累加
text1.setText(String.valueOf(sum));
}
if (sign.equals("-")) {
int no2 = Integer.parseInt(no1);
int no3 = Integer.parseInt(text1.getText());
sum = no2 - no3;
text1.setText(String.valueOf(sum));
}
if (sign.equals("*")) {
int no2 = Integer.parseInt(no1);
int no3 = Integer.parseInt(text1.getText());
sum = no2 * no3;
text1.setText(String.valueOf(sum));
}
if (sign.equals("/")) {
int no2 = Integer.parseInt(no1);
int no3 = Integer.parseInt(text1.getText());
sum = no2 / no3;
text1.setText(String.valueOf(sum));
}
}
});
buttons[15].setBounds(190, 200, 50, 40);
buttons[15].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sb.delete(0, sb.capacity());//清除sb的內容
text1.setText("");//結果框設置為空
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//響應關閉窗口
setVisible(true);//顯示窗口
}
}
2.主程序類
package Calc;
public class CalcTest {
public static void main(String[] args) {
CalcFrame f = new CalcFrame();
}
}
學習Java就到IT學習聯盟
F. 用Java設計一個簡單的計算器。
無聊寫了個,修復了下Bug:
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjavax.swing.JButton;
importjavax.swing.JFrame;
importjavax.swing.JLabel;
importjavax.swing.JOptionPane;
importjavax.swing.JTextField;
{
=1L;
privateJButtonplus,rece,multiply,divice,reset;
privateJTextFieldone,two,result;
privatebooleandevice_falg=false;
privatefinalintwidth=400,height=300;
publicCalculate(){
super("修改密碼");
this.setLayout(null);
this.setSize(width,height);
init();
Layout();
}
publicvoidinit(){
plus=newJButton("加");
rece=newJButton("減");
multiply=newJButton("乘");
divice=newJButton("除");
reset=newJButton("清空");
one=newJTextField();
two=newJTextField();
result=newJTextField();
}
publicvoidLayout(){
this.add(newJLabel("第一個數")).setBounds(20,10,60,80);
this.add(one).setBounds(100,38,100,25);
this.add(newJLabel("第二個數")).setBounds(20,40,60,80);
this.add(two).setBounds(100,70,100,25);
this.add(newJLabel("結果")).setBounds(20,85,60,80);
this.add(result).setBounds(100,110,100,25);
this.add(plus).setBounds(70,170,80,25);
this.add(rece).setBounds(200,170,80,25);
this.add(multiply).setBounds(70,200,80,25);
this.add(divice).setBounds(200,200,80,25);
this.add(reset).setBounds(300,220,80,25);
plus.addActionListener(this);
rece.addActionListener(this);
multiply.addActionListener(this);
divice.addActionListener(this);
reset.addActionListener(this);
this.setVisible(true);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
publicbooleanFormat(){
booleanFLAG=false;
booleanflag=false;
Stringone=this.one.getText().toString().trim();
Stringtwo=this.two.getText().toString().trim();
if(one==null||one.equals("")||two==null||two.equals("")){
JOptionPane.showMessageDialog(getParent(),"請輸入完整信息!");
FLAG=false;
flag=true;
}
booleanboll_1=one.matches("[\d]{1,100}");
booleanboll_2=two.matches("[\d]{1,100}");
booleanboll_3=one.matches("[\d]{1,100}+[.]+[\d]{1,100}");
booleanboll_4=two.matches("[\d]{1,100}+[.]+[\d]{1,100}");
if(flag){
returnfalse;
}
if((boll_1&&boll_2)||(boll_3&&boll_4)||(boll_1&&boll_4)
||(boll_3&&boll_2)){
FLAG=true;
}else{
JOptionPane.showMessageDialog(getParent(),"請輸入數字!");
FLAG=false;
}
if(FLAG&&device_falg){
if(Double.parseDouble(two)==0){
JOptionPane.showMessageDialog(getParent(),"被除數不能為0!");
FLAG=false;
device_falg=false;
}
}
returnFLAG;
}
publicdoublePlus(doubleone,doubletwo){
returnone+two;
}
publicdoubleMultiply(doubleone,doubletwo){
returnone*two;
}
publicdoubleDivice(doubleone,doubletwo){
returnone/two;
}
publicdoubleRece(doubleone,doubletwo){
returnone-two;
}
publicvoidClear(){
one.setText("");
two.setText("");
result.setText("");
}
@Override
publicvoidactionPerformed(ActionEvente){
Objecto=e.getSource();
if(o==reset){
Clear();
return;
}
if(o==divice){
device_falg=true;
}
if(!Format()){
return;
}
doubleone=Double.parseDouble(this.one.getText());
doubletwo=Double.parseDouble(this.two.getText());
doubleresult=0;
if(o==plus){
result=Plus(one,two);
}elseif(o==rece){
result=Rece(one,two);
}elseif(o==multiply){
result=Multiply(one,two);
}elseif(o==divice){
result=Divice(one,two);
}
this.result.setText(""+result);
}
publicstaticvoidmain(String[]args){
newCalculate();
}
}
G. 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放置在窗體的中間
}
}
H. 用java編寫計算器
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JCalculator extends JFrame implements ActionListener {
private static final long serialVersionUID = -L;
private class WindowCloser extends WindowAdapter {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
}
int i;
private final String[] str = { "7", "8", "9", "/", "4", "5", "6", "*", "1",
"2", "3", "-", ".", "0", "=", "+" };
// 建立按鈕
JButton[] buttons = new JButton[str.length];
// 撤銷重置
JButton reset = new JButton("CE");
// 建立文本域顯示結果
JTextField display = new JTextField("0");
public JCalculator() {
super("Calculator");
// 添加一個面板
JPanel panel1 = new JPanel(new GridLayout(4, 4));
// panel1.setLayout(new GridLayout(4,4));
for (i = 0; i < str.length; i++) {
buttons[i] = new JButton(str[i]);
panel1.add(buttons[i]);
}
JPanel panel2 = new JPanel(new BorderLayout());
// panel2.setLayout(new BorderLayout());
panel2.add("Center", display);
panel2.add("East", reset);
// JPanel panel3 = new Panel();
getContentPane().setLayout(new BorderLayout());
getContentPane().add("North", panel2);
getContentPane().add("Center", panel1);
// 添加操作動作的監聽器.
for (i = 0; i < str.length; i++)
buttons[i].addActionListener(this);
// 為重置按鈕添加監聽器
reset.addActionListener(this);
display.addActionListener(this);
// The "close" button "X".
addWindowListener(new WindowCloser());
// Initialize the window size.
setSize(800, 800);
// Show the window.
// show(); Using show() while JDK version is below 1.5.
setVisible(true);
// Fit the certain size.
pack();
}
public void actionPerformed(ActionEvent e) {
Object target = e.getSource();
String label = e.getActionCommand();
if (target == reset)
handleReset();
else if (".".indexOf(label) > 0)
handleNumber(label);
else
handleOperator(label);
}
// Is the first digit pressed?
boolean isFirstDigit = true;
/**
* Number handling.
* @param key the key of the button.
*/
public void handleNumber(String key) {
if (isFirstDigit)
display.setText(key);
else if ((key.equals(".")) (display.getText().indexOf(".") < 0))
display.setText(display.getText() + ".");
else if (!key.equals("."))
display.setText(display.getText() + key);
isFirstDigit = false;
}
/**
* Reset the calculator.
*/
public void handleReset() {
display.setText("0");
isFirstDigit = true;
operator = "=";
}
double number = 0.0;
String operator = "=";
public void handleOperator(String key) {
if (operator.equals("+"))
number += Double.valueOf(display.getText());
else if (operator.equals("-"))
number -= Double.valueOf(display.getText());
else if (operator.equals("*"))
number *= Double.valueOf(display.getText());
else if (operator.equals("/"))
number /= Double.valueOf(display.getText());
else if (operator.equals("="))
number = Double.valueOf(display.getText());
display.setText(String.valueOf(number));
operator = key;
isFirstDigit = true;
}
public static void main(String[] args) {
new JCalculator();
}
}
I. 用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可以直接運行了