21xrx.com
2024-11-22 15:09:41 Friday
登录
文章检索 我的文章 写文章
我喜欢用Java编写计算器
2023-06-10 08:31:51 深夜i     --     --

我喜欢用Java编写计算器,因为它可以帮助我快速实现基础操作和高级运算。下面,我将分享一些Java计算器的例子。

首先,我们可以使用Java的swing库来构建简单的图形用户界面(GUI)。以下是一个基本的GUI计算器的代码示例:


import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class Calculator extends JFrame implements ActionListener {

  JButton b1, b2, b3, b4, b5, b6, b7, b8, b9, b0, bAdd, bSub, bMul, bDiv, bDot, bClear, bEq;

  JTextField tf;

  double num1, num2, result;

  int operator;

  Calculator() {

    tf = new JTextField();

    b1 = new JButton("1");

    b2 = new JButton("2");

    b3 = new JButton("3");

    b4 = new JButton("4");

    b5 = new JButton("5");

    b6 = new JButton("6");

    b7 = new JButton("7");

    b8 = new JButton("8");

    b9 = new JButton("9");

    b0 = new JButton("0");

    bAdd = new JButton("+");

    bSub = new JButton("-");

    bMul = new JButton("*");

    bDiv = new JButton("/");

    bDot = new JButton(".");

    bClear = new JButton("Clear");

    bEq = new JButton("=");

    tf.setBounds(30, 40, 280, 30);

    b7.setBounds(40, 100, 50, 40);

    b8.setBounds(110, 100, 50, 40);

    b9.setBounds(180, 100, 50, 40);

    bDiv.setBounds(250, 100, 50, 40);

    b4.setBounds(40, 170, 50, 40);

    b5.setBounds(110, 170, 50, 40);

    b6.setBounds(180, 170, 50, 40);

    bMul.setBounds(250, 170, 50, 40);

    b1.setBounds(40, 240, 50, 40);

    b2.setBounds(110, 240, 50, 40);

    b3.setBounds(180, 240, 50, 40);

    bSub.setBounds(250, 240, 50, 40);

    bDot.setBounds(40, 310, 50, 40);

    b0.setBounds(110, 310, 50, 40);

    bClear.setBounds(180, 310, 100, 40);

    bAdd.setBounds(250, 310, 50, 40);

    bEq.setBounds(150, 380, 100, 40);

    add(tf);

    add(b7);

    add(b8);

    add(b9);

    add(bDiv);

    add(b4);

    add(b5);

    add(b6);

    add(bMul);

    add(b1);

    add(b2);

    add(b3);

    add(bSub);

    add(bDot);

    add(b0);

    add(bClear);

    add(bAdd);

    add(bEq);

    setLayout(null);

    setVisible(true);

    setSize(350,450);

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    b1.addActionListener(this);

    b2.addActionListener(this);

    b3.addActionListener(this);

    b4.addActionListener(this);

    b5.addActionListener(this);

    b6.addActionListener(this);

    b7.addActionListener(this);

    b8.addActionListener(this);

    b9.addActionListener(this);

    b0.addActionListener(this);

    bAdd.addActionListener(this);

    bSub.addActionListener(this);

    bMul.addActionListener(this);

    bDiv.addActionListener(this);

    bDot.addActionListener(this);

    bClear.addActionListener(this);

    bEq.addActionListener(this);

  }

  public void actionPerformed(ActionEvent e) {

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

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

    }

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

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

    }

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

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

    }

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

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

    }

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

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

    }

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

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

    }

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

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

    }

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

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

    }

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

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

    }

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

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

    }

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

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

    }

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

      num1 = Double.parseDouble(tf.getText());

      operator = 1;

      tf.setText("");

    }

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

      num1 = Double.parseDouble(tf.getText());

      operator = 2;

      tf.setText("");

    }

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

      num1 = Double.parseDouble(tf.getText());

      operator = 3;

      tf.setText("");

    }

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

      num1 = Double.parseDouble(tf.getText());

      operator = 4;

      tf.setText("");

    }

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

      num2 = Double.parseDouble(tf.getText());

      switch (operator) {

        case 1:

          result = num1 + num2;

          break;

        case 2:

          result = num1 - num2;

          break;

        case 3:

          result = num1 * num2;

          break;

        case 4:

          result = num1 / num2;

          break;

        default:

          result = 0;

      }

      tf.setText("" + result);

    }

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

      tf.setText("");

    }

  }

  public static void main(String[] args) {

    Calculator c = new Calculator();

  }

}

该计算器支持数字输入、加、减、乘、除、小数、清除和求值的基本功能。使用ActionListener类对按钮事件的处理进行编程。

其次,Java也支持使用命令行界面(CLI)构建计算器。下面是一个普通的Java CLI计算器的代码示例:


import java.util.Scanner;

public class Calculator {

  public static void main(String[] args) {

    double num1, num2, result;

    Scanner scanner = new Scanner(System.in);

    System.out.print("Enter first number: ");

    num1 = scanner.nextDouble();

    System.out.print("Enter second number: ");

    num2 = scanner.nextDouble();

    System.out.print("Enter an operator (+, -, *, /): ");

    char operator = scanner.next().charAt(0);

    scanner.close();

    switch(operator) {

      case '+':

        result = num1 + num2;

        break;

      case '-':

        result = num1 - num2;

        break;

      case '*':

        result = num1 * num2;

        break;

      case '/':

        result = num1 / num2;

        break;

      default:

        System.out.println("Invalid operator");

        return;

    }

    System.out.println(num1 + " " + operator + " " + num2 + " = " + result);

  }

}

此计算器使用Scanner类从命令行获取输入。它支持加、减、乘、除运算符,并在控制台上输出结果。

最后,Java还支持使用其他框架,如JavaFX和Swing,构建复杂的计算器应用程序。应用程序可以包括例如图形化界面、历史记录、变量存储和自定义函数等高级功能。下面是JavaFX计算器的代码示例:


import javafx.application.Application;

import javafx.event.ActionEvent;

import javafx.event.EventHandler;

import javafx.geometry.Insets;

import javafx.scene.Scene;

import javafx.scene.control.*;

import javafx.scene.layout.GridPane;

import javafx.stage.Stage;

public class Calculator extends Application {

  private TextField output;

  private double savedValue = 0;

  private String lastOperator = "";

  @Override

  public void start(Stage primaryStage) throws Exception {

    GridPane root = new GridPane();

    root.setPadding(new Insets(10));

    root.setHgap(5);

    root.setVgap(5);

    output = new TextField("0");

    output.setEditable(false);

    output.setPrefWidth(200);

    root.add(output, 0, 0, 4, 1);

    Button btn1 = new Button("1");

    btn1.setOnAction(event -> startNumber("1"));

    root.add(btn1, 0, 1);

    Button btn2 = new Button("2");

    btn2.setOnAction(event -> startNumber("2"));

    root.add(btn2, 1, 1);

    Button btn3 = new Button("3");

    btn3.setOnAction(event -> startNumber("3"));

    root.add(btn3, 2, 1);

    Button btnPlus = new Button("+");

    btnPlus.setOnAction(event -> startOperator("+"));

    root.add(btnPlus, 3, 1);

    Button btn4 = new Button("4");

    btn4.setOnAction(event -> startNumber("4"));

    root.add(btn4, 0, 2);

    Button btn5 = new Button("5");

    btn5.setOnAction(event -> startNumber("5"));

    root.add(btn5, 1, 2);

    Button btn6 = new Button("6");

    btn6.setOnAction(event -> startNumber("6"));

    root.add(btn6, 2, 2);

    Button btnMinus = new Button("-");

    btnMinus.setOnAction(event -> startOperator("-"));

    root.add(btnMinus, 3, 2);

    Button btn7 = new Button("7");

    btn7.setOnAction(event -> startNumber("7"));

    root.add(btn7, 0, 3);

    Button btn8 = new Button("8");

    btn8.setOnAction(event -> startNumber("8"));

    root.add(btn8, 1, 3);

    Button btn9 = new Button("9");

    btn9.setOnAction(event -> startNumber("9"));

    root.add(btn9, 2, 3);

    Button btnMultiply = new Button("*");

    btnMultiply.setOnAction(event -> startOperator("*"));

    root.add(btnMultiply, 3, 3);

    Button btn0 = new Button("0");

    btn0.setOnAction(event -> startNumber("0"));

    root.add(btn0, 0, 4);

    Button btnEquals = new Button("=");

    btnEquals.setOnAction(event -> calculateResult());

    root.add(btnEquals, 1, 4);

    Button btnClear = new Button("C");

    btnClear.setOnAction(event -> clear());

    root.add(btnClear, 2, 4);

    Button btnDivide = new Button("/");

    btnDivide.setOnAction(event -> startOperator("/"));

    root.add(btnDivide, 3, 4);

    primaryStage.setTitle("Calculator");

    primaryStage.setScene(new Scene(root));

    primaryStage.show();

  }

  private void startNumber(String number) {

    if (output.getText().equals("0")) {

      output.setText(number);

    } else {

      output.setText(output.getText() + number);

    }

  }

  private void startOperator(String operator) {

    savedValue = Double.parseDouble(output.getText());

    output.setText("0");

    lastOperator = operator;

  }

  private void calculateResult() {

    double value = Double.parseDouble(output.getText());

    double result;

    switch (lastOperator) {

      case "+":

        result = savedValue + value;

        break;

      case "-":

        result = savedValue - value;

        break;

      case "*":

        result = savedValue * value;

        break;

      case "/":

        result = savedValue / value;

        break;

      default:

        result = value;

    }

    savedValue = result;

    output.setText(Double.toString(result));

  }

  private void clear() {

    output.setText("0");

    savedValue = 0;

    lastOperator = "";

  }

  public static void main(String[] args) {

    launch(args);

  }

}

该计算器使用JavaFX构建,支持数字输入、四种基本运算和清除功能。代码使用lambda表达式注册事件处理程序。

综上可知,Java提供了多种类型的计算器实现方式,包括基于GUI和CLI的简单计算器以及基于框架的复杂计算器应用程序。这为数学计算和应用程序开发提供了很大的帮助。

  
  

评论区

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