您的位置:首页 > 编程语言 > Java开发

【练习题】构造方法 编写Java程序,模拟简单的计算器。

2017-11-19 17:31 756 查看
package day09;
/*1.【练习题】构造方法
编写Java程序,模拟简单的计算器。
定义名为Number的类,其中有两个整型数据成员n1和n2,应声明为私有。编写构造方法,赋予n1和n2初始值,再为该类定义加(addition)、减(subtration)、乘(multiplication)、除(division)等公有成员方法,分别对两个成员
变量执行加、减、乘、除的运算。
在main方法中创建Number类的对象,调用各个方法,并显示计算结果。 */
public class HomeWork_01 {

public static void main(String[] args) {
//		Number s1 = new Number();  //备注掉的是无参构造部分,成员方法改void,不要return,改out输出
Number s1 = new Number(5,1);
//		s1.setN1(5);
//		s1.setN2(1);
int sum = s1.addition();
int div = s1.division();
int sub = s1.subtration();
int mul = s1.multiplication();
System.out.println("和为:" + sum + ",相减为:" + sub + ",相乘为:" + mul + ",相除为:" + div);

}

}

class Number {
private int n1;
private int n2;

public Number(int n1 ,int n2){
this.n1 =n1;
this.n2 =n2;
//不加this会导致
//Unresolved compilation problem:未编译的问题:
//The constructor Number() is undefined 构造函数号()没有定义
}

//	public int getN1() {
//		return n1;
//	}
//
//	public void setN1(int n1) {
//		this.n1 = n1;
//	}
//
//	public int getN2() {
//		return n2;
//	}
//
//	public void setN2(int n2) {
//		this.n2 = n2;
//	}
//
//	public Number() {
//		this.n1 = 0;
//		this.n2 = 0;
//	}

public int addition() {
return n1 + n2;
}

public int subtration() {
return n1 - n2;
}

public int multiplication() {
return n1 * n2;
}

public int division() {
return n1 / n2;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: