题解 | #简单计算器#

简单计算器

https://www.nowcoder.com/practice/b8f770674ba7468bb0a0efcc2aa3a239

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String expression = scanner.nextLine();

        String[] parts = expression.split("\\+|\\-|\\*|\\/");
        if (parts.length!= 2) {
            System.out.println("Invalid operation!");
            return;
        }

        double num1 = Double.parseDouble(parts[0]);
        double num2 = Double.parseDouble(parts[1]);
        char operator = expression.charAt(parts[0].length());

        switch (operator) {
            case '+':
                System.out.printf("%.4f+%.4f=%.4f%n", num1, num2, num1 + num2);
                break;
            case '-':
                System.out.printf("%.4f-%.4f=%.4f%n", num1, num2, num1 - num2);
                break;
            case '*':
                System.out.printf("%.4f*%.4f=%.4f%n", num1, num2, num1 * num2);
                break;
            case '/':
                if (num2 == 0) {
                    System.out.println("Wrong!Division by zero!");
                } else {
                    System.out.printf("%.4f/%.4f=%.4f%n", num1, num2, num1 / num2);
                }
                break;
            default:
                System.out.println("Invalid operation!");
        }
    }
}

全部评论

相关推荐

无情咸鱼王的秋招日记之薛定谔的Offer:好拒信,偷了,希望有机会用到
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务