21xrx.com
2024-12-23 07:11:42 Monday
登录
文章检索 我的文章 写文章
关键词:Java、计算器、代码
2023-06-15 14:36:34 深夜i     --     --

Java编程简易计算器代码大全

在Java编程中,计算器是一个很常见的应用场景。无论是作为学习Java语言基础还是实现具体业务逻辑,编写一个简易计算器代码都是非常有必要的。下面,我们将介绍Java编程中实现计算器的相关代码,帮助初学者快速掌握编码技巧。

1. 计算器基础代码

这是一个比较基础的计算器实现代码,包含加、减、乘、除四个基本运算,使用了Java的Scanner类来实现用户输入,代码如下:


import java.util.Scanner;

public class Calculator {

  public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);

    System.out.print("请输入第一个数字:");

    double num1 = scanner.nextDouble();

    System.out.print("请输入第二个数字:");

    double num2 = scanner.nextDouble();

    System.out.print("请输入要进行的运算(+、-、*、/):");

    String operator = scanner.next();

    double result;

    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("输入的运算符不合法");

        return;

    }

    System.out.println("计算结果为:" + result);

  }

}

2. 计算器带函数代码

在计算器的基础上,我们可以为其添加更多的功能,比如自定义函数。下面是一个带函数的计算器实现代码,用户可以输入一个包含函数调用的数学表达式,程序会自动计算结果。代码如下:


import java.util.Scanner;

public class FunctionCalculator {

  public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);

    System.out.print("请输入表达式:");

    String expr = scanner.nextLine();

    double result = calculate(expr);

    System.out.println("计算结果为:" + result);

  }

  private static double calculate(String expr) {

    int index = expr.indexOf("(");

    while (index != -1) {

      int endIndex = getEndIndex(expr, index);

      String functionExpr = expr.substring(index + 1, endIndex);

      double functionResult = evaluateFunction(functionExpr);

      expr = expr.substring(0, index) + functionResult + expr.substring(endIndex + 1);

      index = expr.indexOf("(");

    }

    return evaluateFunction(expr);

  }

  private static int getEndIndex(String expr, int startIndex) {

    int count = 1;

    for (int i = startIndex + 1; i < expr.length(); i++) {

      if (expr.charAt(i) == '(') {

        count++;

      } else if (expr.charAt(i) == ')') {

        count--;

        if (count == 0) {

          return i;

        }

      }

    }

    return -1;

  }

  private static double evaluateFunction(String expr) {

    if (expr.matches("^-?\\d+(\\.\\d+)?$")) {

      return Double.parseDouble(expr);

    }

    int index = getOperatorIndex(expr, "=", "+-");

    String functionName = expr.substring(0, index);

    String[] args = expr.substring(index + 1).split(",");

    double[] argValues = new double[args.length];

    for (int i = 0; i < args.length; i++) {

      argValues[i] = evaluateFunction(args[i]);

    }

    return callFunction(functionName, argValues);

  }

  private static int getOperatorIndex(String expr, String operators, String excludeOperators) {

    int count = 0;

    for (int i = 0; i < expr.length(); i++) {

      char ch = expr.charAt(i);

      if (operators.indexOf(ch) != -1 && excludeOperators.indexOf(ch) == -1 && count == 0) {

        return i;

      } else if (ch == '(') {

        count++;

      } else if (ch == ')') {

        count--;

      }

    }

    return -1;

  }

  private static double callFunction(String functionName, double[] args) {

    switch (functionName) {

      case "sin":

        return Math.sin(args[0]);

      case "cos":

        return Math.cos(args[0]);

      case "tan":

        return Math.tan(args[0]);

      case "sqrt":

        return Math.sqrt(args[0]);

      case "pow":

        return Math.pow(args[0], args[1]);

      case "log10":

        return Math.log10(args[0]);

      case "log":

        return Math.log(args[0]);

      default:

        throw new IllegalArgumentException("Unknown function: " + functionName);

    }

  }

}

3. 计算器GUI程序代码

除了基于控制台的计算器程序,我们还可以开发一个图形界面GUI的计算器程序。下面是一个用Java Swing编写的简单计算器GUI程序代码,它支持基本运算和三角函数计算,并提供了输入框和按钮控件。代码如下:


import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class CalculatorGUI extends JFrame {

  private JTextField inputTextField;

  private JButton[] operatorButtons;

  private JButton[] functionButtons;

  private JButton[] digitButtons;

  public CalculatorGUI() {

    initUI();

    pack();

    setLocationRelativeTo(null);

    setVisible(true);

  }

  private void initUI() {

    setTitle("计算器");

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    inputTextField = new JTextField(20);

    inputTextField.setEditable(false);

    JPanel operatorPanel = new JPanel(new GridLayout(4, 1, 5, 5));

    operatorButtons = new JButton[4];

    operatorButtons[0] = new JButton("+");

    operatorButtons[0].addActionListener(new OperatorActionListener());

    operatorButtons[1] = new JButton("-");

    operatorButtons[1].addActionListener(new OperatorActionListener());

    operatorButtons[2] = new JButton("*");

    operatorButtons[2].addActionListener(new OperatorActionListener());

    operatorButtons[3] = new JButton("/");

    operatorButtons[3].addActionListener(new OperatorActionListener());

    for (JButton button : operatorButtons) {

      operatorPanel.add(button);

    }

    JPanel functionPanel = new JPanel(new GridLayout(3, 1, 5, 5));

    functionButtons = new JButton[3];

    functionButtons[0] = new JButton("sin");

    functionButtons[0].addActionListener(new FunctionActionListener());

    functionButtons[1] = new JButton("cos");

    functionButtons[1].addActionListener(new FunctionActionListener());

    functionButtons[2] = new JButton("tan");

    functionButtons[2].addActionListener(new FunctionActionListener());

    for (JButton button : functionButtons) {

      functionPanel.add(button);

    }

    JPanel digitPanel = new JPanel(new GridLayout(4, 3, 5, 5));

    digitButtons = new JButton[10];

    for (int i = 1; i < 10; i++) {

      digitButtons[i] = new JButton(String.valueOf(i));

    }

    digitButtons[0] = new JButton("0");

    for (JButton button : digitButtons) {

      button.addActionListener(new DigitActionListener());

      digitPanel.add(button);

    }

    JPanel buttonPanel = new JPanel(new GridLayout(1, 3, 5, 5));

    buttonPanel.add(operatorPanel);

    buttonPanel.add(functionPanel);

    buttonPanel.add(digitPanel);

    getContentPane().add(inputTextField, BorderLayout.NORTH);

    getContentPane().add(buttonPanel, BorderLayout.CENTER);

  }

  private class OperatorActionListener implements ActionListener {

    @Override

    public void actionPerformed(ActionEvent e) {

      String operator = ((JButton) e.getSource()).getText();

      String inputText = inputTextField.getText();

      if (inputText.length() == 0 || inputText.endsWith("(") || inputText.endsWith("sin(") || inputText.endsWith("cos(") || inputText.endsWith("tan(")) {

        return;

      }

      inputTextField.setText(inputText + operator);

    }

  }

  private class FunctionActionListener implements ActionListener {

    @Override

    public void actionPerformed(ActionEvent e) {

      String function = ((JButton) e.getSource()).getText();

      String inputText = inputTextField.getText();

      if (inputText.length() == 0 || inputText.endsWith("(") || Character.isDigit(inputText.charAt(inputText.length() - 1))) {

        inputTextField.setText(inputText + function + "(");

      }

    }

  }

  private class DigitActionListener implements ActionListener {

    @Override

    public void actionPerformed(ActionEvent e) {

      String digit = ((JButton) e.getSource()).getText();

      String inputText = inputTextField.getText();

      inputTextField.setText(inputText + digit);

    }

  }

  public static void main(String[] args) {

    new CalculatorGUI();

  }

}

总结

以上是Java编程中实现计算器的相关代码,包括基础计算器代码、带函数的计算器代码和GUI程序代码。这些代码可以帮助初学者了解Java编程的基础语法和面向对象编程的思想,同时也为实际业务开发提供了一些参考。需要注意的是,这些代码都是基础实现,实际开发中需要根据具体需求进行扩展和优化。

  
  

评论区

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