Java----类和对象(练习题)

编写一个类Calculator,有两个属性num1,num2,这两个数据的值,不能在定义的同时初始化,最后实现加减乘 除四种运算.

public class HomeWork {
	public static void main(String[] args) {
		Scanner scan0 = new Scanner(System.in);
		Scanner scan1 = new Scanner(System.in);
		while(true) {
			int x = scan0.nextInt();
			int y = scan1.nextInt();
			Calculator calculator = new Calculator(x, y);
			System.out.println(x + " + " + y + "= " + calculator.add());
			System.out.println(x + " - " + y + "= " + calculator.sub());
			System.out.println(x + " * " + y + "= " + calculator.mul());
			System.out.println(x + " / " + y + "= " + calculator.dev());
		}
	}
}
class Calculator {
	private  int num1;
	private  int num2;
	public int add() {
		return this.num1 +this.num2;
	}
	public int sub() {
		return this.num1 -this.num2;
	}
	public int mul() {
		return this.num1 *this.num2;
	}
	public double dev() {
		double ret = (double)this.num1 / this.num2;
		return ret;
	}
	public Calculator(int num1, int num2) {
		this.num1 = num1;
		this.num2 = num2;
	}
}

实现交换两个变量的值。要求:需要交换实参的值

public class HomeWork0 {
	public static void main(String[] args) {
		System.out.println("第一种");
		int[] arr = {10,20};
		System.out.println("交换前"+Arrays.toString(arr));
		swap(arr);
		System.out.println("交换后"+Arrays.toString(arr));

		System.out.println();

		System.out.println("第二种");
		MyValue myValue1 = new MyValue();
		myValue1.val = 1;
		MyValue myValue2 = new MyValue();
		myValue2.val = 2;
		System.out.println("交换前: "+myValue1.val+" "+myValue2.val);
		swap(myValue1,myValue2);
		System.out.println("交换后: "+myValue1.val+" "+myValue2.val);

	}
	public static void swap(MyValue myValue1,MyValue myValue2) {
		int tmp = myValue1.val;
		myValue1.val = myValue2.val;
		myValue2.val = tmp;
	}
	public static void swap(int[] arr) {
		int tmp = arr[0];
		arr[0] = arr[1];
		arr[1] = tmp;
	}
}
class MyValue {
	public int val;
}
  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

twelve1959

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值