使用 Java 实现一个简单计算器

在本程序中,您将学习使用 Java 中的 switch..case 制作一个简单的计算器。该计算器将能够对两个数字进行加、减、乘、除运算。

要理解此示例,您应该具备以下 Java 编程的知识:

示例:使用 Java switch 语句的简单计算器

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {

    char operator;
    Double number1, number2, result;

    // create an object of Scanner class
    Scanner input = new Scanner(System.in);

    // ask users to enter operator
    System.out.println("Choose an operator: +, -, *, or /");
    operator = input.next().charAt(0);

    // ask users to enter numbers
    System.out.println("Enter first number");
    number1 = input.nextDouble();

    System.out.println("Enter second number");
    number2 = input.nextDouble();

    switch (operator) {

      // performs addition between numbers
      case '+':
        result = number1 + number2;
        System.out.println(number1 + " + " + number2 + " = " + result);
        break;

      // performs subtraction between numbers
      case '-':
        result = number1 - number2;
        System.out.println(number1 + " - " + number2 + " = " + result);
        break;

      // performs multiplication between numbers
      case '*':
        result = number1 * number2;
        System.out.println(number1 + " * " + number2 + " = " + result);
        break;

      // performs division between numbers
      case '/':
        result = number1 / number2;
        System.out.println(number1 + " / " + number2 + " = " + result);
        break;

      default:
        System.out.println("Invalid operator!");
        break;
    }

    input.close();
  }
}

输出 1

Choose an operator: +, -, *, or /
*
Enter first number
3
Enter second number
9
3.0 * 9.0 = 27.

在这里,我们使用 Scanner 该类从用户那里获取 3 个输入。

  • operator - 指定要执行的操作
  • number1number2 - 要对其执行操作的操作数

由于运算符匹配 case '*' ,因此执行相应的代码。

result = number1 * number2;
System.out.println(number + " * " + number2 + " = " + result);
break;

这些语句计算两个数字的乘积并打印输出。最后,break 语句结束 switch 语句。

同理,对于不同的算子,执行不同的 case。

输出 2

Choose an operator: +, -, *, or /
+
Enter first number
21
Enter second number
8
21.0 + 8.0 = 29.0

输出 3

Choose an operator: +, -, *, or /
-
Enter first number
9
Enter second number
3
9.0 - 3.0 = 6.0

输出 4

Choose an operator: +, -, *, or /
/
Enter first number
24
Enter second number
8
24.0 / 8.0 = 3.0