Java

java实现计算器代码怎么写

小亿
98
2024-02-23 17:18:29
栏目: 编程语言

以下是一个简单的Java计算器代码示例:

import java.util.Scanner;

public class Calculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        System.out.println("Enter the first number: ");
        double num1 = scanner.nextDouble();
        
        System.out.println("Enter the second number: ");
        double num2 = scanner.nextDouble();
        
        System.out.println("Enter the operation (+, -, *, /): ");
        char operation = scanner.next().charAt(0);
        
        double result = 0;
        
        switch(operation) {
            case '+':
                result = num1 + num2;
                break;
            case '-':
                result = num1 - num2;
                break;
            case '*':
                result = num1 * num2;
                break;
            case '/':
                result = num1 / num2;
                break;
            default:
                System.out.println("Invalid operation.");
        }
        
        System.out.println("Result: " + result);
        
        scanner.close();
    }
}

此代码通过用户输入两个数和运算符,然后根据运算符执行相应的运算,最终输出结果。您可以根据自己的需求对此代码进行修改和扩展。

0
看了该问题的人还看了