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