Java基础 4.20

1.类的相关练习

public class Homework01 {
	public static void main(String[] args) {
		A01 a = new A01();
		double[] arr = {};
		Double res = a.max(arr);
		if (res != null) {
			System.out.println("max = " + res);
		} else {
			System.out.println("数组不能为空");
		}
		A02 a2 = new A02();
		String[] arr2 = {"jack", "logic"};
		System.out.println(a2.find(arr2, "jack"));
		Book book = new Book(101, "logic");
		book.updatePrice();
		book.info();
	}
}
//先完成正常业务 再考虑代码的健壮性
//编写类A01 定义方法max 实现求某个double数组的最大值,并返回
class A01 {
	public Double max(double[] arr) {
		//先判断arr是否为空,再判断arr.length是否为0
		if (arr != null && arr.length > 0) {
				double maxnum = arr[0];
			for (int i = 0; i < arr.length; i++) {
				if (maxnum < arr[i]) {
					maxnum = arr[i];
				}
			}
			return maxnum;
		} else {
			return null;
		}
	}
}
//编写类A02 定义方法find 实现查找某字符串是否在数组中 
//并返回索引 如果找不到 返回-1
class A02 {
	public int find(String[] arr, String string) {
		if (arr != null && arr.length > 0) {
				for (int i = 0; i < arr.length; i++) {
				if (arr[i].equals(string)) {
					return i;
				} 			
			} 
			return -1;
		} else {
			return -2;
		}
	}
}

//编写类Book,定义方法updatePrice,实现更改本书的价格
//具体:如果价格>150,则更改为150, 如果价格>100,则更改为100,否则不变
class Book {

	double price;
	String name;
	public Book(double price, String name) {
		this.price = price;
		this.name = name;
	}
	public void updatePrice() {
		//如果方法中,没有price局部变量 this.price等价 price
		if (this.price > 150) {
			this.price = 150;
		} else if (this.price > 100) {
			this.price = 100;
		}
	}

	public void info() {
		System.out.println("book price = " + price);
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值