java定义计算器类Calc:求两个数字加、减、乘、除的结果。创建一个对象,实例化两个数字和符号,输出结果
时间: 2024-03-20 17:45:30 浏览: 298
Java计算器设计-calc
好的,我知道了。以下是Java定义计算器类Calc并实现求两个数字加、减、乘、除的结果的代码:
```java
public class Calc {
private double num1;
private double num2;
public Calc(double num1, double num2) {
this.num1 = num1;
this.num2 = num2;
}
public double add() {
return num1 + num2;
}
public double subtract() {
return num1 - num2;
}
public double multiply() {
return num1 * num2;
}
public double divide() {
if (num2 == 0) {
throw new ArithmeticException("Cannot divide by zero!");
}
return num1 / num2;
}
}
```
然后我们可以创建一个对象并实例化两个数字和符号,输出结果:
```java
public static void main(String[] args) {
double num1 = 10.0;
double num2 = 5.0;
String symbol = "+";
Calc calc = new Calc(num1, num2);
switch (symbol) {
case "+":
System.out.println(num1 + " + " + num2 + " = " + calc.add());
break;
case "-":
System.out.println(num1 + " - " + num2 + " = " + calc.subtract());
break;
case "*":
System.out.println(num1 + " * " + num2 + " = " + calc.multiply());
break;
case "/":
System.out.println(num1 + " / " + num2 + " = " + calc.divide());
break;
default:
System.out.println("Invalid symbol!");
}
}
```
输出结果如下:
```
10.0 + 5.0 = 15.0
```
如果符号是其他的,比如 `-` ,输出结果会是:
```
10.0 - 5.0 = 5.0
```
以此类推。
阅读全文