21xrx.com
2024-12-27 20:48:43 Friday
登录
文章检索 我的文章 写文章
Java计算器程序:打造简洁高效的计算器
2023-06-12 03:58:59 深夜i     --     --
Java 计算器 Swing

Java是一种使用广泛的编程语言,可以用来制作各种应用程序,其中计算器程序是最基本的应用程序之一。本文将介绍如何使用Java语言编写一个简洁高效的计算器程序,并提供相应的代码案例。

首先,在Java中实现计算器程序需要使用Swing库,它是Java图形用户界面(GUI)工具包之一。通过Swing库,我们可以创建各种简单和复杂的GUI元素如按钮、文本框和标签等。下面是一个简单的Java计算器代码示例:

 java

package calculator;

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class Calculator extends JFrame implements ActionListener {

  private JTextField textField;

  private JButton button1, button2, button3, button4, button5, button6, button7, button8, button9, button0, buttonPlus, buttonMinus, buttonDivide, buttonMultiply, buttonEqual, buttonClear;

  public Calculator() {

    // 设置界面标题

    setTitle("Java Calculator");

    // 创建组件

    textField = new JTextField(20);

    textField.setHorizontalAlignment(JTextField.RIGHT);

    button1 = new JButton("1");

    button2 = new JButton("2");

    button3 = new JButton("3");

    button4 = new JButton("4");

    button5 = new JButton("5");

    button6 = new JButton("6");

    button7 = new JButton("7");

    button8 = new JButton("8");

    button9 = new JButton("9");

    button0 = new JButton("0");

    buttonPlus = new JButton("+");

    buttonMinus = new JButton("-");

    buttonDivide = new JButton("/");

    buttonMultiply = new JButton("*");

    buttonEqual = new JButton("=");

    buttonClear = new JButton("C");

    // 添加事件监听器

    button1.addActionListener(this);

    button2.addActionListener(this);

    button3.addActionListener(this);

    button4.addActionListener(this);

    button5.addActionListener(this);

    button6.addActionListener(this);

    button7.addActionListener(this);

    button8.addActionListener(this);

    button9.addActionListener(this);

    button0.addActionListener(this);

    buttonPlus.addActionListener(this);

    buttonMinus.addActionListener(this);

    buttonDivide.addActionListener(this);

    buttonMultiply.addActionListener(this);

    buttonEqual.addActionListener(this);

    buttonClear.addActionListener(this);

    // 添加组件到界面

    JPanel panel1 = new JPanel(new GridLayout(1, 1, 5, 5));

    panel1.add(textField);

    JPanel panel2 = new JPanel(new GridLayout(4, 4, 5, 5));

    panel2.add(button1);

    panel2.add(button2);

    panel2.add(button3);

    panel2.add(buttonPlus);

    panel2.add(button4);

    panel2.add(button5);

    panel2.add(button6);

    panel2.add(buttonMinus);

    panel2.add(button7);

    panel2.add(button8);

    panel2.add(button9);

    panel2.add(buttonMultiply);

    panel2.add(buttonClear);

    panel2.add(button0);

    panel2.add(buttonEqual);

    panel2.add(buttonDivide);

    add(panel1, BorderLayout.NORTH);

    add(panel2, BorderLayout.CENTER);

    // 设置界面

    setSize(250, 250);

    setVisible(true);

    setResizable(false);

    setLocationRelativeTo(null);

  }

  public void actionPerformed(ActionEvent e) {

    if (e.getSource() == button1) {

      textField.setText(textField.getText() + "1");

    } else if (e.getSource() == button2) {

      textField.setText(textField.getText() + "2");

    } else if (e.getSource() == button3) {

      textField.setText(textField.getText() + "3");

    } else if (e.getSource() == button4) {

      textField.setText(textField.getText() + "4");

    } else if (e.getSource() == button5) {

      textField.setText(textField.getText() + "5");

    } else if (e.getSource() == button6) {

      textField.setText(textField.getText() + "6");

    } else if (e.getSource() == button7) {

      textField.setText(textField.getText() + "7");

    } else if (e.getSource() == button8) {

      textField.setText(textField.getText() + "8");

    } else if (e.getSource() == button9) {

      textField.setText(textField.getText() + "9");

    } else if (e.getSource() == button0) {

      textField.setText(textField.getText() + "0");

    } else if (e.getSource() == buttonPlus) {

      textField.setText(textField.getText() + "+");

    } else if (e.getSource() == buttonMinus) {

      textField.setText(textField.getText() + "-");

    } else if (e.getSource() == buttonDivide) {

      textField.setText(textField.getText() + "/");

    } else if (e.getSource() == buttonMultiply) {

      textField.setText(textField.getText() + "*");

    } else if (e.getSource() == buttonClear) {

      textField.setText("");

    } else if (e.getSource() == buttonEqual) {

      String exp = textField.getText();

      int result = evaluateExpression(exp);

      textField.setText(Integer.toString(result));

    }

  }

  public static void main(String[] args) {

    new Calculator();

  }

  public static int evaluateExpression(String exp) {

    //根据输入的算式求出结果

    return new Object() {

      int pos = -1, ch;

      void nextChar() {

        ch = (++pos < exp.length()) ? exp.charAt(pos) : -1;

      }

      boolean eat(int charToEat) {

        while (ch == ' ') nextChar();

        if (ch == charToEat) {

          nextChar();

          return true;

        }

        return false;

      }

      int parse() {

        nextChar();

        int x = parseExpression();

        if (pos < exp.length()) throw new RuntimeException("Unexpected: " + (char) ch);

        return x;

      }

      int parseExpression() {

        int x = parseTerm();

        for (; ; ) {

          if (eat('+')) x += parseTerm();

          else if (eat('-')) x -= parseTerm();

          else return x;

        }

      }

      int parseTerm() {

        int x = parseFactor();

        for (; ; ) {

          if (eat('*')) x *= parseFactor();

          else if (eat('/')) x /= parseFactor();

          else return x;

        }

      }

      int parseFactor() {

        if (eat('+')) return parseFactor();

        if (eat('-')) return -parseFactor();

        int x;

        int startPos = this.pos;

        if (eat('(')) {

          x = parseExpression();

          eat(')');

        } else if ((ch >= '0' && ch <= '9') || ch == '-') {

          while ((ch >= '0' && ch <= '9') || ch == '-') nextChar();

          x = Integer.parseInt(exp.substring(startPos, this.pos));

        } else {

          throw new RuntimeException("Unexpected: " + (char) ch);

        }

        return x;

      }

    }.parse();

  }

}

在这个示例中,我们创建了一个Calculator类作为程序的主类,继承了JFrame类。我们使用了JTextField、JButton和JPanel等Swing组件,并为每个按钮添加了事件监听器。我们还提供了一个evaluateExpression函数,它使用了递归下降解析器(recursive descent parser)来计算表达式的值。

通过这个程序,我们可以实现一个功能完整的Java计算器,用户可以输入各种算术运算符号和数字,程序将会自动计算结果并显示在文本框中。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复