.构造方法 编写Java程序模拟简单的计算器。 定义名为Number的类其中有两个整型数据成员n1和n2应声明为私有。 编写构造方法赋予n1和n2初始值再为该类定义加addition、减subtration、乘multiplication、 除division等公有成员方法分别对两个成员变量执行加、减、乘、除的运算。 在main方法中创建Number类的对象调用各个方法并显示计算结果
时间: 2023-11-10 20:05:13 浏览: 105
好的,以下是Java程序的实现:
```java
public class Number {
private int n1;
private int n2;
public Number(int n1, int n2) {
this.n1 = n1;
this.n2 = n2;
}
public int addition() {
return n1 + n2;
}
public int subtraction() {
return n1 - n2;
}
public int multiplication() {
return n1 * n2;
}
public double division() {
return (double) n1 / n2;
}
public static void main(String[] args) {
Number num = new Number(10, 5);
System.out.println("n1 + n2 = " + num.addition());
System.out.println("n1 - n2 = " + num.subtraction());
System.out.println("n1 * n2 = " + num.multiplication());
System.out.println("n1 / n2 = " + num.division());
}
}
```
运行结果:
```
n1 + n2 = 15
n1 - n2 = 5
n1 * n2 = 50
n1 / n2 = 2.0
```
阅读全文