用Java 类写出以上题目
时间: 2024-03-23 19:38:49 浏览: 96
好的,这是一个用 Java 写的计算器类的示例代码:
```java
import java.util.Scanner;
public class Calculation {
private double num1;
private double num2;
public Calculation(double num1, double num2) {
this.num1 = num1;
this.num2 = num2;
}
public double add() {
return this.num1 + this.num2;
}
public double sub() {
return this.num1 - this.num2;
}
public double times() {
return this.num1 * this.num2;
}
public double div() {
if (this.num2 == 0) {
System.out.println("Error: division by zero");
return 0;
} else {
return this.num1 / this.num2;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the first number: ");
double num1 = sc.nextDouble();
System.out.print("Enter the second number: ");
double num2 = sc.nextDouble();
Calculation calc = new Calculation(num1, num2);
System.out.println("Addition: " + calc.add());
System.out.println("Subtraction: " + calc.sub());
System.out.println("Multiplication: " + calc.times());
System.out.println("Division: " + calc.div());
sc.close();
}
}
```
你可以在控制台上输入两个数字,然后调用 `add()`、`sub()`、`times()`、`div()` 方法,分别进行加、减、乘、除的计算。
阅读全文