先完成正常业务,然后再考虑代码健壮性
- 题目要求:
编写类A01,定义方法max,实现求某个double数组的最大值,并返回。
-
代码健壮性考虑:要保证arr至少有一个元素
-
ps:
1)此处可考虑将max函数返回类型设定为Double,因为包装类型可以为null,但是基本数据类型不可为空,此处返回值可以复制为main函数中的res来保证程序健壮性。
2)double数组可以设置为null,所以if中除了只判断length还需判断arr是否为null
//2024.07.13
public class Homework01 {
public static void main(String[] args) {
// double[] arr = {1, 4.3, 3,2};
// double[] arr = {1};
double[] arr = null;
A01 a = new A01();
Double res = a.max(arr);
if (res != null) {
System.out.println("max = " + a.max(arr));
}else{
System.out.println("arr length cannot be less than 0!");
}
}
}
class A01 {
public Double max(double[] arr){
if (arr != null && arr.length > 0) {
double max = arr[0];
for (int i = 0; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}else{
return null;
}
}
}