1)创建一个数学运算接口(Operation),其方法operate用于对两个实数进行算术运算,并返回运算结果。 2)编写加(Addition)、减(Subtraction)、乘(Multiplication)和除(Division)等类实现该接口,并完成相应的算术运算。 3)编写测试类,从键盘接收两个实数,通过Operation的对象计算它们加减乘除的结果并输出。 用Java编写
时间: 2024-01-17 12:03:10 浏览: 174
好的,我可以回答这个问题。以下是Java实现:
首先,我们需要创建一个 Operation 接口,该接口有一个 operate() 方法用于执行算术运算:
```java
public interface Operation {
double operate(double a, double b);
}
```
接下来,我们可以创建加法、减法、乘法和除法类,来实现 Operation 接口:
```java
public class Addition implements Operation {
public double operate(double a, double b) {
return a + b;
}
}
public class Subtraction implements Operation {
public double operate(double a, double b) {
return a - b;
}
}
public class Multiplication implements Operation {
public double operate(double a, double b) {
return a * b;
}
}
public class Division implements Operation {
public double operate(double a, double b) {
if (b == 0) {
throw new IllegalArgumentException("Cannot divide by zero!");
}
return a / b;
}
}
```
最后,我们需要编写一个测试类,从键盘输入两个实数并选择想要执行的算术运算,然后使用相应的类来执行运算并输出结果:
```java
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
double a = scanner.nextDouble();
System.out.print("Enter the second number: ");
double b = scanner.nextDouble();
System.out.println("Select an operation:");
System.out.println("1. Addition (+)");
System.out.println("2. Subtraction (-)");
System.out.println("3. Multiplication (*)");
System.out.println("4. Division (/)");
int choice = scanner.nextInt();
Operation operation;
switch (choice) {
case 1:
operation = new Addition();
break;
case 2:
operation = new Subtraction();
break;
case 3:
operation = new Multiplication();
break;
case 4:
operation = new Division();
break;
default:
System.out.println("Invalid choice!");
return;
}
double result = operation.operate(a, b);
System.out.println("Result: " + result);
}
}
```
这样,我们就完成了一个简单的计算器程序。
阅读全文