1. 程式人生 > >使用java開發簡單計算器介面,並實現加、減、乘、除運算

使用java開發簡單計算器介面,並實現加、減、乘、除運算

最近 老師佈置了java作業,開發一個計算器,並實現+ -  *  / 運算,我寫 了一個。不知道我的思路對不對,希望路過的大神提供一點建議。一些簡單的運算沒有問題。問題是按照我的思路負數不知道怎麼實現,也就是沒有乘於一個負數,或加上一個負數,或減去一個負數,或除於一個負數的功能。為了給其他人蔘考方便,我把程式碼只寫在了一個類裡面。

以下是程式碼

package com.it.xiaojia;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
public class Demo extends JFrame {
	private JFrame jf=new JFrame("Calculator"); //視窗
	private JPanel centerPanel=new JPanel();    //中間面板
	private JPanel bottomPanel=new JPanel();    //底部面板
	
	//中間三個按鈕
	private JButton Backbtn=new JButton("Back");
	private JButton CEbtn=new JButton("CE");
	private JButton Cbtn=new JButton("C");
	
	//初始化功能鍵
	String[] nums={"7","8","9","+","4","5","6","-","1","2","3","*","0",".","=","/"};
	private JButton btn7=new JButton(nums[0]);
	private JButton btn8=new JButton(nums[1]);
	private JButton btn9=new JButton(nums[2]);
	private JButton btnAdd=new JButton(nums[3]);
	private JButton btn4=new JButton(nums[4]);
	private JButton btn5=new JButton(nums[5]);
	private JButton btn6=new JButton(nums[6]);
	private JButton btnMimus=new JButton(nums[7]);
	private JButton btn1=new JButton(nums[8]);
	private JButton btn2=new JButton(nums[9]);
	private JButton btn3=new JButton(nums[10]);
	private JButton btnMultipus=new JButton(nums[11]);
	private JButton btn0=new JButton(nums[12]);
	private JButton btnDot=new JButton(nums[13]);
	private JButton btnResult=new JButton(nums[14]);
	private JButton btnDivide=new JButton(nums[15]);
	
	//單行輸入文字框
	private JTextField txt=new JTextField(15);
	private List<String>lists=new ArrayList<String>(); //用來記錄使用者輸入的數字和操作符
	
	//主函式,程式入口
	public static void main(String[] args){
		try {
			new Demo().init();
		} catch (Exception e) {
			System.out.println("程式異常終止");
			System.exit(0);   //退出虛擬機器
		}
	}
	//初始化
	public void init() throws Exception{
		//使用網格佈局方式
		bottomPanel.setLayout(new GridLayout(4,4,3,3)); //左右上下間隔是3
		//將功能鍵新增到底部面板中
		bottomPanel.add(btn7);
		bottomPanel.add(btn8);
		bottomPanel.add(btn9);
		bottomPanel.add(btnAdd);
		bottomPanel.add(btn4);
		bottomPanel.add(btn5);
		bottomPanel.add(btn6);
		bottomPanel.add(btnMimus);
		bottomPanel.add(btn1);
		bottomPanel.add(btn2);
		bottomPanel.add(btn3);
		bottomPanel.add(btnMultipus);
		bottomPanel.add(btn0);
		bottomPanel.add(btnDot);
		bottomPanel.add(btnResult);
		bottomPanel.add(btnDivide);
		
		//將中間的三個按鈕新增到中間面板
		centerPanel.add(Backbtn);
		centerPanel.add(CEbtn);
		centerPanel.add(Cbtn);
		
		jf.add(txt,BorderLayout.NORTH);   //將單行文字框新增到視窗的 北部
		jf.add(centerPanel);              //將中間面板新增到視窗中間(預設是中間)
		jf.add(bottomPanel,BorderLayout.SOUTH);  //將底部面板新增到視窗的南部
		
		//為C按鈕新增事件監聽
		Cbtn.addActionListener(e->{
			lists.clear();    //將集合中的資料清零
			txt.setText("");  //將 文字域的 值設定為空
		});
		//為Back按鈕新增事件監聽         使用Lamdba表示式
		Backbtn.addActionListener(e->{
			String text=txt.getText(); //得到輸入框文字
			if("".equals(text) || text.length()==1){ 
				txt.setText(""); //如果是空文字或者文字長度為1,直接設為空
				return;
			}
			if(text.length()>1){ //如果文字的長度大於1就要向前擷取
				text=text.substring(0,text.length()-1);
				txt.setText(text);
			}
		});
		
		//為CE按鈕新增事件監聽
		CEbtn.addActionListener(e->{
			//得到輸入文字框
			String text=txt.getText();
			if("".equals(text)){
				return;
			}
			if("+".equals(text) || "-".equals(text) || "*".equals(text) || "/".equals(text)){
				//表示要把+ - * /清除,所以要把集合中的第一個數也移除集合(因為使用者可能點了+的時候,就點CE鍵,此時如果再點數字鍵就會出現問題)
				lists.remove(0);
			}
			txt.setText("");  //把文字直接清掉
		});
		
		//為數字按鈕新增監聽事件     使用匿名內部類
		ActionListener numBtnListener=new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				//得到輸入文字框的內容
				String text=txt.getText();
				//判斷有沒有這句話 (0不能做分母,請清零後重試),如果有 ,當點選數字按鈕的時候要它消失
				if("除數不能為0".equals(text)){
					txt.setText(e.getActionCommand());
					return;
				}
				//如果第一個數是0,就不能輸入其他數字了,只能輸入小數點了
				if("0".equals(text)){
					return;
				}
				if("".equals(text)){  //當文字域中沒資料的時候,把當前點選的數字顯示上去
					txt.setText(e.getActionCommand());
				}else{
					//如果當前輸入框有資料,並且是操作符時,記錄下該操作符
					if(text.equals("+") || text.equals("-") || text.equals("*") || text.equals("/")){
						lists.add(text);  //將操作符新增到集合中
						txt.setText("");
						text=""; //將得到的文字符空,也就是將+或-或 *或/賦空值
					}
					text+=e.getActionCommand();
					txt.setText(text);
				}
			}
		};
		//為數字註冊 監聽器
		btn1.addActionListener(numBtnListener);
		btn2.addActionListener(numBtnListener);
		btn3.addActionListener(numBtnListener);
		btn4.addActionListener(numBtnListener);
		btn5.addActionListener(numBtnListener);
		btn6.addActionListener(numBtnListener);
		btn7.addActionListener(numBtnListener);
		btn8.addActionListener(numBtnListener);
		btn9.addActionListener(numBtnListener);
		
		//為0按鈕新增事件監聽
		btn0.addActionListener(e->{
			//得到輸入文字框
			String text=txt.getText();
			if("0".equals(text)){  //如果第一個數是0,不能再出現0了
				return;
			}
			//如果出現操作符,就記錄下來
			if("+".equals(text) || "-".equals(text) || "*".equals(text) || "/".equals(text)){
				lists.add(text);
				text="";  //把操作符情況
			}
			text+=e.getActionCommand();
			txt.setText(text);
		});
		//為點  .按鈕 新增事件監聽  使用Lamdba表示式
		btnDot.addActionListener(e->{
			//得到輸入文字框
			String text=txt.getText();
			if("".equals(text)){
				return;
			}
			//判斷文字是否為+ - * / .
			if("+".equals(text) || "-".equals(text) || "*".equals(text) || "/".equals(text)){
				return;
			}
			//如果該數字後面已經有小數點了,那麼就不能連續出現兩次小數點了
			if(text.contains(".")){
				return;
			}
			text+=e.getActionCommand();
			txt.setText(text); //設定進去
		});
		
		//為+-*/新增事件監聽    使用匿名內部類  
		ActionListener operationBtnListener=new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				//獲取輸入文字框內的內容
				String text=txt.getText();
				if("".equals(text)){
					return;
				}
				if("+".equals(text) || "-".equals(text) || "*".equals(text) || "/".equals(text)){
					return;
				}
				//將內容新增到集合中
				lists.add(text);
				//將輸入框清空
				txt.setText("");
				//把按鈕上面的字顯示進去
				txt.setText(e.getActionCommand());
			}
		};
		//為* - + /註冊監聽器
		btnAdd.addActionListener(operationBtnListener);
		btnMimus.addActionListener(operationBtnListener);
		btnMultipus.addActionListener(operationBtnListener);
		btnDivide.addActionListener(operationBtnListener);
		
		//為 =按鈕新增事件監聽
		ActionListener resultBtnListener=new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				//判斷集合中的資料
				if(lists.isEmpty()){
					return;
				}
				//獲取文字輸入框的內容
				String text=txt.getText();
				if("".equals(txt) || "+".equals(text) || "-".equals(text) || "*".equals(text) || "/".equals(text)){
					return;
				}
				//將其新增到集合中
				lists.add(text);
				if(lists.size()<3){
					return;
				}
				String one=lists.get(0);  //得到集合中的第一個數
				String two=lists.get(1); //得到集合中的第二個數
				String three=lists.get(2); //得到集合中的第三個數
				switch(two){
				case "+":
					double i=Double.parseDouble(one);
					double j=Double.parseDouble(three);
					txt.setText((i+j)+""); //顯示結果
					break;
				case "-":
					double x=Double.parseDouble(one);
					double y=Double.parseDouble(three);
					txt.setText((x-y)+""); //顯示結果
					break;
					
				case "*":
					double a=Double.parseDouble(one);
					double b=Double.parseDouble(three);
					txt.setText((a*b)+"");
					break;
				case "/":
					double k=Double.parseDouble(one);
					double h=Double.parseDouble(three);
					if(h==0){
						txt.setText("除數不能為0");
						lists.clear();
						return;
					}
					txt.setText((k/h)+"");
					break;
				}
				//將集合中的資料清空
				lists.clear();
			}
		};
		//為=等號按鈕註冊監聽器
		btnResult.addActionListener(resultBtnListener);
		//自定義視窗的圖示
		ImageIcon image=new ImageIcon("image/girl.jpg"); //圖片位置
		image.setImage(image.getImage().getScaledInstance(30,30,Image.SCALE_DEFAULT));
		jf.setIconImage(image.getImage());
		//設定UI的風格為Nimbus
		UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
		//更新f視窗內所有元件的UI
		SwingUtilities.updateComponentTreeUI(jf.getContentPane());
		jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//點X關閉視窗
		jf.setLocation(400, 200); //初始化時定位
		jf.setResizable(false);   //禁止拖曳改變視窗大小
		jf.pack();               //讓視窗的大小自適應
		jf.setVisible(true);  //顯示視窗
	}
}


2,下面是執行效果