编写一个简易的计算器程序,实现加减乘除等运算。
时间: 2024-12-21 21:27:44 浏览: 15
当然,我可以帮你编写一个简单的控制台版四则运算计算器程序。这个程序将会使用基本的控制台输入和处理逻辑。让我们从创建一个`Calculator`类开始,该类包含四个方法分别对应加、减、乘、除操作:
```java
public class Calculator {
// 加法方法
public double add(double num1, double num2) {
return num1 + num2;
}
// 减法方法
public double subtract(double num1, double num2) {
return num1 - num2;
}
// 乘法方法
public double multiply(double num1, double num2) {
return num1 * num2;
}
// 除法方法(需要注意除数不能为0)
public double divide(double num1, double num2) throws ArithmeticException {
if (num2 == 0) {
throw new ArithmeticException("Division by zero is not allowed.");
}
return num1 / num2;
}
}
```
然后你可以创建一个`main`方法来接收用户的输入并调用这些计算方法:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Calculator calculator = new Calculator();
System.out.println("Enter the first number:");
double num1 = scanner.nextDouble();
System.out.println("Enter the operator (+, -, *, /):");
char operator = scanner.next().charAt(0); // 获取第一个字符
System.out.println("Enter the second number:");
switch (operator) {
case '+':
System.out.println("Result: " + calculator.add(num1, scanner.nextDouble()));
break;
case '-':
System.out.println("Result: " + calculator.subtract(num1, scanner.nextDouble()));
break;
case '*':
System.out.println("Result: " + calculator.multiply(num1, scanner.nextDouble()));
break;
case '/':
try {
System.out.println("Result: " + calculator.divide(num1, scanner.nextDouble()));
} catch (ArithmeticException e) {
System.out.println(e.getMessage());
}
break;
default:
System.out.println("Invalid operator. Please use one of the following: +, -, *, /");
}
scanner.close();
}
}
```
现在,当你运行这个程序时,它会提示你输入两个数字和运算符,然后输出结果。如果输入了无效的运算符或尝试除以零,它会给出相应的错误消息。
阅读全文