Design a simple calculator program in Java

【introduction】

A calculator is a common tool used to perform basic mathematical operations. In computer science, we can use programming languages ​​to simulate and implement a calculator program. This article will design and implement a simple calculator program based on Java language.

【text】

1. Need analysis

Before designing a calculator program, we need to clarify the program's requirements. The calculator program designed in this article should meet the following functions:

  • Supports the four basic arithmetic operations (addition, subtraction, multiplication, division);
  • Support multiple operations;
  • Provides the function to clear results;
  • Able to handle illegal input (such as dividing by zero);
  • Provides a friendly user interface to facilitate users to input operands and operators.

2. Design ideas

Based on the above requirements, we will design a Calculator class to implement the calculator program. This class will contain the following member variables and methods:

  • Member variables: used to store calculation results;
  • Construction method: initialize calculation results;
  • Get result method: return calculation result;
  • Addition method: accepts an operand and adds it to the result;
  • Subtraction method: accepts an operand and subtracts it from the result;
  • Multiplication method: accepts an operand and multiplies it by the result;
  • Division method: accepts an operand and divides the result by it;
  • Clear method: Resets the result to zero.

3. Design and implementation

The following is the design and implementation of a simple Java calculator program:

public class Calculator {
    private double result; // 存储计算结果

    public Calculator() {
        result = 0;
    }

    public double getResult() {
        return result;
    }

    public void add(double num) {
        result += num;
    }

    public void subtract(double num) {
        result -= num;
    }

    public void multiply(double num) {
        result *= num;
    }

    public void divide(double num) {
        if (num == 0) {
            System.out.println("Error: divide by zero");
        } else {
            result /= num;
        }
    }

    public void clear() {
        result = 0;
    }
}

4. User interaction

To make the calculator program interactive, we can use the Scanner class to get input from the user. In the main function, we can create a Calculator object, obtain the numbers and operators entered by the user through the Scanner, and then call the corresponding method of the Calculator object to perform calculations.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Calculator calculator = new Calculator();
        Scanner scanner = new Scanner(System.in);

        while (true) {
            System.out.println("请输入数字和操作符(+、-、*、/),用空格分隔,输入q退出:");
            String input = scanner.nextLine();

            if (input.equals("q")) {
                break;
            }

            String[] tokens = input.split(" ");
            double num = Double.parseDouble(tokens[0]);
            char op = tokens[1].charAt(0);

            switch (op) {
                case '+':
                    calculator.add(num);
                    break;
                case '-':
                    calculator.subtract(num);
                    break;
                case '*':
                    calculator.multiply(num);
                    break;
                case '/':
                    calculator.divide(num);
                    break;
                default:
                    System.out.println("Error: invalid operator");
            }

            System.out.println("Result: " + calculator.getResult());
        }
    }
}

5. Extended functions

The above calculator program has simple functions, but it can be used as a practice project for learning basic Java syntax. If we need to expand functionality, we can add more operators or support calculations with multiple operands. For example, we can add exponentiation, square root, remainder, etc. At the same time, we can also introduce bracket operations and priority processing to enable the calculator to handle complex expressions.

【Summarize】

This article designs and implements a simple calculator program based on Java language. By defining the Calculator class and using the Scanner class to implement user interaction, we can perform the four basic arithmetic operations and obtain the final calculation result. The calculator program is extensible and more functions can be added according to actual needs. By writing such small projects, we not only consolidated Java syntax, but also learned object-oriented design and development ideas. I hope that by reading this article, readers can have a deeper understanding of the basic knowledge of Java and be able to use the knowledge they have learned to develop more complex projects.

Guess you like

Origin blog.csdn.net/hitpter/article/details/133480680