Java 实例 使用Switch Case制作计算器

在本程序中,我们正在制作一个简单的计算器,根据用户输入执行加法,减法,乘法和除法。程序获取两个数字的值(由用户输入),然后要求用户输入操作(+-*/),根据输入程序使用对输入的数字执行所选操作switch-case

示例:使用的switch case编写计算器的程序

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);
    }
}

输出:

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

Java 示例