JAVA实现“简易计算器”

//package work;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Calculator extends JFrame implements ActionListener {
	// 属性
	JTextField txtResult;
	boolean firstDigit = true;//用于判断是否是数字
	String operator = "=";//先初始化为等号,等到执行相应运算时再更改
	boolean operateValidFlag = true;//判断除数是否为0
	double resultNum = 0.0;//可以暂存目前的最终结果
	// 方法
	public Calculator() {
		setTitle("计算器");
		setSize(500, 500);
		setResizable(false);
		setLocationRelativeTo(null);
		setDefaultCloseOperation(EXIT_ON_CLOSE);

		Container contentPane = this.getContentPane();
		contentPane.setLayout(new BorderLayout(1, 5));
		JPanel pnlNorth = new JPanel();
		JPanel pnlCenter = new JPanel();

		pnlNorth.setLayout(new BorderLayout());
		pnlCenter.setLayout(new GridLayout(4, 4, 3, 3));

		Font font = new Font("Times Roman", Font.BOLD, 20);

		contentPane.add(BorderLayout.NORTH, pnlNorth);
		contentPane.add(BorderLayout.CENTER, pnlCenter);

		txtResult = new JTextField();
		txtResult.setFont(font);
		txtResult.setEnabled(false);
		JButton btnClear = new JButton("CE");
		btnClear.setFont(font);
		btnClear.addActionListener(this);

		pnlNorth.add(BorderLayout.CENTER, txtResult);
		pnlNorth.add(BorderLayout.EAST, btnClear);

		String[] captions = { "7", "8", "9", "+", "4", "5", "6", "-", "1", "2", "3", "*", "0", ".", "/", "=", };
		for (int i = 0; i < captions.length; i++) {
			JButton btn = new JButton(captions[i]);
			btn.setFont(font);
			pnlCenter.add(btn);
			btn.addActionListener(this);
			
		}
	
	}

	public static void main(String[] args) {
		JFrame frame = new Calculator();
		frame.setVisible(true);
	}
	//对按钮进行的反应
	@Override
	public void actionPerformed(ActionEvent event) {
		String label = event.getActionCommand();
		 if (label.equals("CE") ){
			handleC();
		} else if ("0123456789.".indexOf(label) >= 0) {
			//无论整数还是小数都一起提取出来
			handleNumber(label);
		} else {
			//将当前要执行的运算的运算符赋给operator
			handleOperator(label);
		}
	}

	//提取数字
	 void handleNumber(String key) {
		if (firstDigit) {
			txtResult.setText(key);//在文本框中显示数字的字符串
		} else if ((key.equals(".")) && (txtResult.getText().indexOf(".") < 0)) {
			
			txtResult.setText(txtResult.getText() + ".");//在文本框中显示整数数字的字符串
		} else if (!key.equals(".")) {
		
			txtResult.setText(txtResult.getText() + key);//在文本框中显示整数数字的字符串
		}
		firstDigit = false;//当数字显示完之后,即可重置为false
	}

	 //实现清零
	 void handleC() {

		 txtResult.setText("0");
		firstDigit = true;
		operator = "=";
	}
//进行运算
  void handleOperator(String key) {
		if (operator.equals("/")) {
			//判断除数是否为0
			if (getNumberFromText() == 0.0) {
	
				operateValidFlag = false;
				txtResult.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) {
				txtResult.setText(String.valueOf(t1));
			} else {
				txtResult.setText(String.valueOf(resultNum));
			}
		}
		operator = key;
		firstDigit = true;
		operateValidFlag = true;
	}

	 double getNumberFromText() {
		double result = 0;
		try {
			result = Double.valueOf(txtResult.getText()).doubleValue();//把String转化成Double类型的对象,并求double的原始值
		} catch (NumberFormatException e) {
		}
		return result;
	}
		/*
		// JOptionPane.showMessageDialog(this, event.getActionCommand());
		String cmd = event.getActionCommand();
		
		 if ("0123456789+-/*.".contains(cmd)) {
			// JOptionPane.showMessageDialog(this, "数字");
			txtResult.setText(txtResult.getText() + cmd);
		}
		String s = txtResult.getText().split("");// 提取文本框内的内容
       //运算在这里进行
		if ("C".equals(cmd)) {
			txtResult.setText("");
		}

		result(s);
	}
	public void result(String [] s) {
		if ("=".equals(s[s.length])) {
			// JOptionPane.showMessageDialog(this, "等于");
			
			//JOptionPane.showMessageDialog(this, Arrays.toString(s));//检查输入的字符串有无错误
			double temp = 0, result = 0;// temp用于暂存数据,result用于存放当前计算结果
			int loc = 0;// 记录一些特殊字符的位置
			int flag=0;
			//遍历这个字符数组
			for (int m = 0; m < s.length-1;) {
				if ("0123456789".contains(s[m])) {
					flag=1;
					temp = temp * 10 + Integer.parseInt(s[m]);
					m++;
				}
				if (".".equals(s[m]))// 开始记录小数
				{
					loc = m;// 锁定小数点的位置
					double temp0 = 0;// 用于存储小数
					while ("0123456789".contains(s[loc + 1])) {
						loc++;
						temp0 = temp0 * 10 + Integer.parseInt(s[loc]);
					}
					while (temp0 > 1)// 将小数点后的数变为小数
					{
						temp0 = temp0 / 10;
					}
					temp = temp + temp0;
					m=loc+1;
				}
				//运算符
				if ("+".equals(s[m])&&flag==1) {
					flag=0;
					result = result + temp;
					m++;
				}
				if ("-".equals(s[m])&&flag==1) {
					flag=0;
					result = result - temp;
					m++;
				}
				if ("*".equals(s[m])&&flag==1) {
					flag=0;
					loc = m;
					double temp1 = 0;// 用于存储下一个数
					while ("0123456789".contains(s[loc + 1])) {
						loc++;
						temp1 = temp1 * 10 + Integer.parseInt(s[loc]);
					}
					result = result + temp * temp1;
					m=loc+1;
				}
				if ("/".equals(s[m])&&flag==1) {
					flag=0;
					loc = m;
					double temp2 = 0;// 用于存储下一个数
					while ("0123456789".contains(s[loc + 1])) {
						loc++;
						temp2 = temp2 * 10 + Integer.parseInt(s[loc]);
					}
					if(temp2==0)
					{
						System.out.println("除数不能为零");
					}
					else {
						result = result + temp / temp2;
						m=loc+1;
					}
				}
			}
			// 显示最终结果
			txtResult.setText("");// 先清空所有显示数据
			txtResult.setText(String.valueOf(result));			
		}*/
	}

 

你可能感兴趣的:(项目)