用Java设计一个简单的计算器。

设计一个简单的计算器,能够对两个数据进行“加、减、乘、除”运算。要求:合理应用布局设计,注重界面美观、友好,要求处理NumberFormatException异常。

果果果大美 2021-09-18 16:36 150 次浏览 赞 132

最新问答

  • 0密星猛龙0

    说实在的,你写的这个计算器不怎么样。特别是布局。
    我给你一个很简单的吧。你自己学习一下。。

    import java.awt.*;
    import java.awt.event.*;
    /**
    *
    * @author zzj
    *
    */
    public class Jisuanqi extends WindowAdapter {
    Panel p1 = new Panel();
    Panel p2 = new Panel();
    Panel p3 = new Panel();
    TextField txt;
    private Button[] b = new Button[17];
    private String ss[] = { "7", "8", "9", "+", "4", "5", "6", "-", "1", "2",
    "3", "*", "清空", "0", "=", "/", "关闭" };
    static double a;
    static String s, str;//定义变量 创建对像

    public static void main(String args[]) {
    (new Jisuanqi()).frame();
    }

    public void frame() {
    Frame fm = new Frame("简单计算器");
    for (int i = 0; i <= 16; i++) {
    b[i] = new Button(ss[i]);
    }
    for (int i = 0; i <= 15; i++) {
    p2.add(b[i]);
    } //创建按钮 并到P2
    b[16].setBackground(Color.yellow);
    txt = new TextField(15);
    txt.setEditable(false);
    for (int i = 0; i <= 16; i++) {
    b[i].addActionListener(new buttonlistener());//
    }
    b[16].addActionListener(new close());
    fm.addWindowListener(this);
    fm.setBackground(Color.red);
    p1.setLayout(new BorderLayout());
    p1.add(txt, "North");
    p2.setLayout(new GridLayout(4, 4));
    p3.setLayout(new BorderLayout());
    p3.add(b[16]);
    fm.add(p1, "North");
    fm.add(p2, "Center");
    fm.add(p3, "South");
    fm.pack();
    fm.setVisible(true);//都是些窗中设置 相关组件和
    }

    public void windowClosing(WindowEvent e) {
    System.exit(0);//退出系统
    }

    class buttonlistener implements ActionListener {//编写 通过按键得出给果
    public void actionPerformed(ActionEvent e) {
    Button btn = (Button) e.getSource();
    if (btn.getLabel() == "=") {
    jisuan();
    str = String.valueOf(a);
    txt.setText(str);
    s = "";
    } else if (btn.getLabel() == "+") {
    jisuan();
    txt.setText("");
    s = "+";
    } else if (btn.getLabel() == "-") {
    jisuan();
    txt.setText("");
    s = "-";
    } else if (btn.getLabel() == "/") {
    jisuan();
    txt.setText("");
    s = "/";

    } else if (btn.getLabel() == "*") {
    jisuan();
    txt.setText("");
    s = "*";
    } else {
    txt.setText(txt.getText() + btn.getLabel());

    if (btn.getLabel() == "清空")
    txt.setText("");
    }
    }

    public void jisuan() {//编写具体计算方法
    if (s == "+")
    a += Double.parseDouble(txt.getText());
    else if (s == "-")
    a -= Double.parseDouble(txt.getText());
    else if (s == "*")
    a *= Double.parseDouble(txt.getText());
    else if (s == "/")
    a /= Double.parseDouble(txt.getText());
    else
    a = Double.parseDouble(txt.getText());
    }
    }
    }

    class close implements ActionListener {//退出
    public void actionPerformed(ActionEvent e) {
    System.exit(0);
    }
    }

    浏览 253赞 147时间 2023-10-07
  • 弱智好儿童

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

    public class Calculator extends Applet implements ActionListener{
    Button backButton=new Button("退格");
    Button clearButton=new Button("清除");
    Panel p1 = new Panel(new FlowLayout());
    Panel p2 = new Panel(new GridLayout(2,1));
    Panel p3 = new Panel(new GridLayout(4,5,5,5));
    TextField t=new TextField("0");
    float num1=0;
    char ch='#';boolean can=false;
    public void init(){
    t.setFont(new Font("宋体",Font.BOLD,25));
    backButton.setFont(new Font("黑体",Font.BOLD,15));
    backButton.setForeground(Color.red);
    clearButton.setFont(new Font("黑体",Font.BOLD,15));
    clearButton.setForeground(Color.red);
    p1.add(backButton);
    p1.add(clearButton);
    backButton.addActionListener(this);
    clearButton.addActionListener(this);
    p2.add(t);
    p2.add(p1);
    p2.setBackground(Color.black);
    p3.setBackground(Color.black);
    this.setLayout(new BorderLayout());
    this.add(p2,"North");
    this.add(p3,"Center");
    String buttonStr = "789/A456*B123-C0.D+=";
    for (int i = 0; i < buttonStr.length(); i++)
    this.addButton(p3,buttonStr.substring(i, i + 1));
    }
    private void addButton(Container c, String s)
    {Button b = new Button(s);
    if (s.equals("A"))
    b.setLabel("sqrt");
    else if (s.equals("B"))
    b.setLabel("1/x");
    else if (s.equals("C"))
    b.setLabel("%");
    else if (s.equals("D"))
    b.setLabel("+/-");
    b.setForeground(Color.blue);
    b.setFont(new Font("黑体",Font.BOLD,15));
    c.add(b);
    b.addActionListener(this);
    }
    public void actionPerformed(ActionEvent e){
    String act=e.getActionCommand();
    if(e.getSource()==backButton){
    if(t.getText().length()>1)t.setText(t.getText().substring(0, t.getText().length()-1));
    else t.setText("0");
    return;}
    if(e.getSource()==clearButton){t.setText("0");ch='#';return;}
    if(act.equals("+/-")){
    if(t.getText().charAt(0)!='-')t.setText("-"+t.getText());
    else t.setText(t.getText().substring(1));return;
    }
    if(act.equals(".")){t.setText(t.getText()+act);return;}
    if(act!="1/x"&&act.charAt(0)>='0'&&act.charAt(0)<='9'){
    if(can){t.setText(act);can=false;}
    else{try{if(Float.parseFloat(t.getText())==0)
    {if(t.getText().equals("0."))t.setText(t.getText()+act);
    else t.setText(act);
    return;
    }
    else {t.setText(t.getText()+act);return;}
    }catch(NumberFormatException e1){
    JOptionPane.showMessageDialog(null, "输入格式错误!", "警告!",
    JOptionPane.ERROR_MESSAGE);return;}
    }
    }

    if(act.equals("+")||act.equals("-")||act.equals("*")||act.equals("/")||act.equals("%")){
    if(ch!='#'){try{num1=cacu(num1,ch,Float.parseFloat(t.getText()));
    t.setText(String.valueOf(num1));ch=act.charAt(0);can=true;return;
    }catch(NumberFormatException e1){JOptionPane.showMessageDialog(null, "输入格式错误!", "警告!",
    JOptionPane.ERROR_MESSAGE);return;}
    }
    else{try{num1=Float.parseFloat(t.getText());
    ch=act.charAt(0);can=true;return;
    }catch(NumberFormatException e1){JOptionPane.showMessageDialog(null, "输入格式错误!", "警告!",
    JOptionPane.ERROR_MESSAGE);return;}
    }
    }
    if(act.equals("sqrt")){try{float num=(float)Math.sqrt(Float.parseFloat(t.getText()));
    t.setText(String.valueOf(num));can=true;return;
    }catch(NumberFormatException e1){JOptionPane.showMessageDialog(null, "输入格式错误!", "警告!",
    JOptionPane.ERROR_MESSAGE);return;}
    }
    if(act.equals("1/x")){try{float num=1/Float.parseFloat(t.getText());
    t.setText(String.valueOf(num));can=true;return;
    }catch(NumberFormatException e1){JOptionPane.showMessageDialog(null, "输入格式错误!", "警告!",
    JOptionPane.ERROR_MESSAGE);return;}
    catch(ArithmeticException e1){JOptionPane.showMessageDialog(null, "除0错误!", "警告!",
    JOptionPane.ERROR_MESSAGE);return;}
    }
    if(act.equals("=")){can=true;
    try{if(ch=='#')return;
    float num=Float.parseFloat(t.getText());
    num1=cacu(num1,ch,num);
    t.setText(String.valueOf(num1));
    ch='#';return;
    }catch(NumberFormatException e1){JOptionPane.showMessageDialog(null, "输入格式错误!", "警告!",
    JOptionPane.ERROR_MESSAGE);return;}
    }
    }
    public float cacu(float a,char c,float b){
    float sum;
    switch(c){
    case '+':sum=a+b;break;
    case '-':sum=a-b;break;
    case '*':sum=a*b;break;
    case '/':if(b==0){JOptionPane.showMessageDialog(null, "除0错误!", "警告!",
    JOptionPane.ERROR_MESSAGE);return 0;}sum=a/b;break;
    case '%':if(b==0){JOptionPane.showMessageDialog(null, "除0错误!", "警告!",
    JOptionPane.ERROR_MESSAGE);return 0;}sum=a%b;break;
    default:return 0;
    }
    return sum;
    }
    }

    浏览 376赞 64时间 2023-09-30
  • Lemonice柠檬冰

    无聊写了个,修复了下Bug:

    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JTextField;

    public class Calculate extends JFrame implements ActionListener {

    private static final long serialVersionUID = 1L;

    private JButton plus, reduce, multiply, divice, reset;
    private JTextField one, two, result;
    private boolean device_falg = false;

    private final int width = 400, height = 300;

    public Calculate() {
    super("修改密");
    this.setLayout(null);
    this.setSize(width, height);
    init();
    Layout();
    }

    public void init() {
    plus = new JButton("加 ");
    reduce = new JButton("减 ");
    multiply = new JButton("乘 ");
    divice = new JButton("除 ");
    reset = new JButton("清空");
    one = new JTextField();
    two = new JTextField();
    result = new JTextField();
    }

    public void Layout() {
    this.add(new JLabel("第一个数")).setBounds(20, 10, 60, 80);
    this.add(one).setBounds(100, 38, 100, 25);
    this.add(new JLabel("第二个数")).setBounds(20, 40, 60, 80);
    this.add(two).setBounds(100, 70, 100, 25);
    this.add(new JLabel("结果")).setBounds(20, 85, 60, 80);
    this.add(result).setBounds(100, 110, 100, 25);

    this.add(plus).setBounds(70, 170, 80, 25);
    this.add(reduce).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);
    reduce.addActionListener(this);
    multiply.addActionListener(this);
    divice.addActionListener(this);
    reset.addActionListener(this);

    this.setVisible(true);
    this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }

    public boolean Format() {
    boolean FLAG = false;
    boolean flag = false;
    String one = this.one.getText().toString().trim();
    String two = this.two.getText().toString().trim();

    if (one == null || one.equals("") || two == null || two.equals("")) {
    JOptionPane.showMessageDialog(getParent(), "请输入完整信息!");
    FLAG = false;
    flag = true;
    }

    boolean boll_1 = one.matches("[d]{1,100}");
    boolean boll_2 = two.matches("[d]{1,100}");
    boolean boll_3 = one.matches("[d]{1,100}+[.]+[d]{1,100}");
    boolean boll_4 = two.matches("[d]{1,100}+[.]+[d]{1,100}");
    if (flag) {
    return false;
    }
    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;
    }
    }

    return FLAG;
    }

    public double Plus(double one, double two) {
    return one + two;
    }

    public double Multiply(double one, double two) {
    return one * two;
    }

    public double Divice(double one, double two) {
    return one / two;
    }

    public double Reduce(double one, double two) {
    return one - two;
    }

    public void Clear() {
    one.setText("");
    two.setText("");
    result.setText("");
    }

    @Override
    public void actionPerformed(ActionEvent e) {
    Object o = e.getSource();
    if (o == reset) {
    Clear();
    return;
    }
    if (o == divice) {
    device_falg = true;
    }
    if (!Format()) {
    return;
    }
    double one = Double.parseDouble(this.one.getText());
    double two = Double.parseDouble(this.two.getText());
    double result = 0;
    if (o == plus) {
    result = Plus(one, two);
    } else if (o == reduce) {
    result = Reduce(one, two);
    } else if (o == multiply) {
    result = Multiply(one, two);
    } else if (o == divice) {
    result = Divice(one, two);
    }
    this.result.setText("" + result);
    }
    public static void main(String[] args) {
    new Calculate();
    }
    }

    浏览 482赞 96时间 2022-12-04
  • 早秋2013

    比一楼的简单

    package com.isoftstone.baidu;

    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;

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

    public class CalcDemo extends JFrame {

    private static final long serialVersionUID = 111111L;
    private JLabel label1 = new JLabel();
    private JLabel label2 = new JLabel();
    private JLabel label3 = new JLabel();
    private JTextField field1 = new JTextField();
    private JTextField field2 = new JTextField();
    private JTextField field3 = new JTextField();
    private JButton button1 = new JButton();
    private JButton button2 = new JButton();
    private JButton button3 = new JButton();
    private JButton button4 = new JButton();

    public static void main(String[] args) {
    new CalcDemo();
    }

    public CalcDemo() {
    super("简易计算器");
    try {
    init();
    } catch (Exception e) {
    e.printStackTrace();
    }
    }

    private void init() {
    this.setSize(300, 300);
    label1.setText("第一个数:");
    label2.setText("第二个数:");
    label3.setText("结果:");
    button1.setText("加法");
    button2.setText("减法");
    button3.setText("乘法");
    button4.setText("除法");
    label1.setBounds(10, 10, 100, 22);
    label2.setBounds(10, 35, 100, 22);
    label3.setBounds(10, 60, 100, 22);
    field1.setBounds(110, 10, 100, 22);
    field2.setBounds(110, 35, 100, 22);
    field3.setBounds(110, 60, 100, 22);
    button1.setBounds(10, 85, 100, 22);
    button2.setBounds(110, 85, 100, 22);
    button3.setBounds(110, 110, 100, 22);
    button4.setBounds(10, 110, 100, 22);
    button1.addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {
    calculate(1);
    }
    });
    button2.addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {
    calculate(2);
    }
    });
    button3.addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {
    calculate(3);
    }
    });
    button4.addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {
    calculate(4);
    }
    });
    JPanel panel = (JPanel) this.getContentPane();
    panel.setLayout(null);
    panel.add(label1);
    panel.add(label2);
    panel.add(label3);
    panel.add(field1);
    panel.add(field2);
    panel.add(field3);
    panel.add(button1);
    panel.add(button2);
    panel.add(button3);
    panel.add(button4);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setResizable(false);
    this.setLocationRelativeTo(null);
    this.setVisible(true);

    }

    private void calculate(int operators) {
    try {
    double num1 = Double.parseDouble(field1.getText());
    double num2 = Double.parseDouble(field2.getText());
    switch (operators) {
    case 1:
    field3.setText((num1 + num2) + "");
    break;
    case 2:
    field3.setText((num1 - num2) + "");
    break;
    case 3:
    field3.setText((num1 * num2) + "");
    break;
    case 4:
    field3.setText((num1 / num2) + "");
    break;
    default:
    break;
    }
    } catch (NumberFormatException e) {
    JOptionPane.showMessageDialog(this, "请输入正确的数值!!!", "警告", 1);
    }
    }
    }

    浏览 398赞 72时间 2022-03-24
  • 涅槃0531

    百度一下很多的,何况这代也不难,自己理一下很也能弄出来,给button, 中取两个文本框的值,将两个文本框的值转化为int(这时候可能会有异常,trycatch处理),在进行运算,最后将结果放入结果文本框中

    浏览 296赞 135时间 2021-09-22

用Java设计一个简单的计算器。

设计一个简单的计算器,能够对两个数据进行“加、减、乘、除”运算。要求:合理应用布局设计,注重界面美观、友好,要求处理NumberFormatException异常。