Skip to content

Latest commit

 

History

History
81 lines (55 loc) · 2.42 KB

File metadata and controls

81 lines (55 loc) · 2.42 KB

Java 程序:使用switch...case创建一个简单的计算器

原文: https://www.programiz.com/java-programming/examples/calculator-switch-case

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

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

import java.util.Scanner;

public class Calculator {

    public static void main(String[] args) {

        Scanner reader = new Scanner(System.in);
        System.out.print("Enter two numbers: ");

        // nextDouble() reads the next double from the keyboard
        double first = reader.nextDouble();
        double second = reader.nextDouble();

        System.out.print("Enter an operator (+, -, *, /): ");
        char operator = reader.next().charAt(0);

        double result;

        switch(operator)
        {
            case '+':
                result = first + second;
                break;

            case '-':
                result = first - second;
                break;

            case '*':
                result = first * second;
                break;

            case '/':
                result = first / second;
                break;

            // operator doesn't match any case constant (+, -, *, /)
            default:
                System.out.printf("Error! operator is not correct");
                return;
        }

        System.out.printf("%.1f %c %.1f = %.1f", first, operator, second, result);
    }
}

运行该程序时,输出为:

Enter two numbers: 1.5
4.5
Enter an operator (+, -, *, /): *
1.5 * 4.5 = 6.8

使用Scanner对象的next()方法,将用户输入的*运算符存储在operator变量中。

同样,使用Scanner对象的nextDouble()方法,将两个操作数 1.5 和 4.5 分别存储在变量firstsecond中。

由于运算符*匹配何时条件'*':,因此程序控制跳至

result = first * second;

该语句计算乘积并将结果存入变量resultbreak语句结束switch语句。

最后,执行printf语句。

注意:我们使用了printf()方法而不是println。 这是因为这里我们要打印格式化的字符串。 要了解更多信息,请访问 Java printf()方法