题解 | #简单计算器#
简单计算器
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!"); } } }