# Java 程序：使用`Switch Case`制作计算器

> 原文： [https://beginnersbook.com/2017/09/java-program-to-make-a-calculator-using-switch-case/](https://beginnersbook.com/2017/09/java-program-to-make-a-calculator-using-switch-case/)

在本程序中，我们正在制作一个简单的计算器，根据用户输入执行加法，减法，乘法和除法。程序获取两个数字的值（由用户输入），然后要求用户输入操作（`+`，`-`，`*`和`/`），根据输入程序使用[对输入的数字执行所选操作`switch-case`](https://beginnersbook.com/2017/08/java-switch-case/)。

> 如果您是 java 新手，请参阅 [Java 教程](https://beginnersbook.com/java-tutorial-for-beginners-with-examples/)，从基础开始学习 java 编程。

## 示例：使用的`switch case`编写计算器的程序

```java
import java.util.Scanner;

public class JavaExample {

    public static void main(String[] args) {

    	double num1, num2;
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter first number:");

        /* We are using data type double so that user
         * can enter integer as well as floating point
         * value
         */
        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();
        double output;

        switch(operator)
        {
            case '+':
            	output = num1 + num2;
                break;

            case '-':
            	output = num1 - num2;
                break;

            case '*':
            	output = num1 * num2;
                break;

            case '/':
            	output = num1 / num2;
                break;

            /* If user enters any other operator or char apart from
             * +, -, * and /, then display an error message to user
             * 
             */
            default:
                System.out.printf("You have entered wrong operator");
                return;
        }

        System.out.println(num1+" "+operator+" "+num2+": "+output);
    }
}
```

输出：

```java
Enter first number:40
Enter second number:4
Enter an operator (+, -, *, /): /
40.0 / 4.0: 10.0
```