4、编写Java程序模拟简单的计算器。 定义名为Number的类其中有两个整型数据成员n1和n2应声明为私有。 编写构造方法赋予n1和n2初始值 再为该类定义加addition()、减substation()、乘multiplication()、除division()等公有实例方法 分别对两个成员变量执行加、减、乘、除的运算。 在main方法中创建Number类的对象调用各个方法并显示计算结果
public class HomeWork4 {
public static void main(String[] args) {
Number n1 = new Number(20,30);
System.out.println("两个数字分别是:" + n1.getN1() + "和" + n1.getN2());
n1.addition();
n1.substation();
n1.multiplication();
n1.division();
Number n2 = new Number(20,0);
System.out.println("两个数字分别是:" + n2.getN1() + "和" + n2.getN2());
n2.addition();
n2.substation();
n2.multiplication();
n2.division();
}
}
class Number {
private double n1;
private double n2;
public Number() {
}
public Number(double n1, double n2) {
this.n1 = n1;
this.n2 = n2;
}
public double getN1() {
return n1;
}
public void setN1(double n1) {
this.n1 = n1;
}
public double getN2() {
return n2;
}
public void setN2(double n2) {
this.n2 = n2;
}
public void addition() {
System.out.println(this.getN1() + "+" + this.getN2() + "=" + this.getN1()+this.getN2());
}
public void substation() {
double result = this.getN1()-this.getN2();
System.out.println(this.getN1() + "-" + this.getN2() + "=" + result);
}
public void multiplication() {
System.out.println(this.getN1() + "*" + this.getN2() + "=" + this.getN1()*this.getN2());
}
public void division() {
if(n2 == 0){
System.out.println("除数不能为0!");
return;
}else
System.out.println(this.getN1() + "/" + this.getN2() + "=" + this.getN1()/this.getN2());
}
}
|