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

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;
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值