java中简单的计算器

就这样子喽

有错误麻烦联系我,谢谢~

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class A extends JFrame implements ActionListener {
	JButton button1 = new JButton("输入操作数");
	JButton button2 = new JButton("计算");
	JRadioButton one = new JRadioButton("+");// 添加单选框选择
	JRadioButton two = new JRadioButton("-");
	JRadioButton three = new JRadioButton("*");
	JRadioButton four = new JRadioButton("/");
	ButtonGroup group = new ButtonGroup();// 归组
	int fnumber = 0;// 记录用户输入的值
	int snumber = 0;
	String fuhao;// 记录用户选择的符号
	String regex="[0-9]+";//正则表达式
	public A() {
		setBounds(400, 400, 400, 400);
		setTitle("java");
		setLayout(new FlowLayout());// 窗体初始化数据
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		group.add(one);
		group.add(two);
		group.add(three);
		group.add(four);// 归组
		add(one);
		add(two);
		add(three);
		add(four);
		add(button1);
		add(button2);// 添加到窗体
		one.addActionListener(this);
		two.addActionListener(this);
		three.addActionListener(this);
		four.addActionListener(this);
		button1.addActionListener(this);
		button2.addActionListener(this);// 添加监视器
		setVisible(true);
	}

	public void actionPerformed(ActionEvent a) {
		//用户输入数字,如果取消则不进行强制装换
		if (a.getSource() == button1) {
			String test = JOptionPane.showInputDialog(this, "请输入数字一", "提示信息",JOptionPane.WARNING_MESSAGE);
			if (test != null) {
				if(test.matches(regex)){
					fnumber = Integer.parseInt(test);
					test = JOptionPane.showInputDialog(this, "请输入数字二", "提示信息",JOptionPane.WARNING_MESSAGE);
					if (test != null) {
						if(test.matches(regex)){
							snumber = Integer.parseInt(test);
						}
						else{
							JOptionPane.showMessageDialog(this, "请输入正确的数字", "错误提示",JOptionPane.WARNING_MESSAGE);
						}
					}
				}
				else {
					JOptionPane.showMessageDialog(this, "请输入正确的数字", "错误提示",JOptionPane.WARNING_MESSAGE);
				}
			}
		}
		// 判断用户选择的符号
		else if (a.getSource() == one) {
			fuhao = "+";
		} else if (a.getSource() == two) {
			fuhao = "-";
		} else if (a.getSource() == three) {
			fuhao = "*";
		} else if (a.getSource() == four) {
			fuhao = "/";
		} else if (a.getSource() == button2) {
			// 计算结果并输出
			if (fuhao == null) {
				JOptionPane.showMessageDialog(this, "错误!请选择计算符号!", "提示信息",
						JOptionPane.WARNING_MESSAGE);
			} else if (fnumber != 0 || snumber != 0) {
				if (fuhao.equals("+")) {
					System.out.println(fnumber + snumber);//输出计算结果
				}
				if (fuhao.equals("-")) {
					System.out.println(fnumber - snumber);//输出计算结果
				}
				if (fuhao.equals("*")) {
					System.out.println(fnumber * snumber);//输出计算结果
				}
				if (fuhao.equals("/")) {
					System.out.println(fnumber / snumber);//输出计算结果
				}
			} else {
				JOptionPane.showMessageDialog(this, "错误!请输入数字一或者输入二!", "提示信息",
						JOptionPane.WARNING_MESSAGE);
			}
		}

	}

	public static void main(String[] args) {
		A cc = new A();//创建窗体
	}

}

效果图

在这里插入图片描述

**为什么简单写这么复杂?因为…我疯啦,啦啦啦~~~~~~~**

发布了14 篇原创文章 · 获赞 3 · 访问量 701

猜你喜欢

转载自blog.csdn.net/u014582342/article/details/103492732