- 定义一个Calculator类,用于表示计算器,包括加、减、乘、除等操作,并提供计算结果的方法。
public class Calculator { public static double add(double x, double y) { return x + y; } public static double subtract(double x, double y) { return x - y; } public static double multiply(double x, double y) { return x * y; } public static double divide(double x, double y) { if (y == 0) { throw new IllegalArgumentException("Divisor cannot be zero"); } return x / y; } }
- 在主程序中,接收用户输入的计算表达式,解析表达式中的操作数和操作符,并调用Calculator类中的方法进行计算。
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter expression: "); String expression = scanner.nextLine(); String[] tokens = expression.split(" "); double x = Double.parseDouble(tokens[0]); double y = Double.parseDouble(tokens[2]); String operator = tokens[1]; double result = 0; switch (operator) { case "+": result = Calculator.add(x, y); break; case "-": result = Calculator.subtract(x, y); break; case "*": result = Calculator.multiply(x, y); break; case "/": result = Calculator.divide(x, y); break; default: System.out.println("Invalid operator"); System.exit(0); } System.out.println("Result: " + result); } }
- 在计算器程序中,还可以添加异常处理等功能,例如当用户输入无效的表达式或除数为零时,可以抛出IllegalArgumentException或ArithmeticException等异常,以提高程序的鲁棒性和用户体验。
下面是添加异常处理的代码示例:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter expression: "); String expression = scanner.nextLine(); String[] tokens = expression.split(" "); double x = Double.parseDouble(tokens[0]); double y = Double.parseDouble(tokens[2]); String operator = tokens[1]; double result = 0; try { switch (operator) { case "+": result = Calculator.add(x, y); break; case "-": result = Calculator.subtract(x, y); break; case "*": result = Calculator.multiply(x, y); break; case "/": result = Calculator.divide(x, y); break; default: throw new IllegalArgumentException("Invalid operator"); } System.out.println("Result: " + result); } catch (NumberFormatException e) { System.out.println("Invalid expression"); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); } catch (ArithmeticException e) { System.out.println(e.getMessage()); } } }
在上面的代码中,如果用户输入的表达式无法解析为操作数和操作符,将会抛出NumberFormatException异常;如果用户输入的操作符无效,将会抛出IllegalArgumentException异常;如果用户输入的除数为零,将会抛出ArithmeticException异常。通过添加异常处理,程序可以更加健壮和友好。
评论