Java返回数组最小值时出现“lossy conversion”错误求助
解决数组求最小值时的索引类型错误问题
嗨,我一眼就发现你代码里的问题啦!你把循环计数器counter定义成了double类型,但Java数组的索引必须是整数类型(比如int),用double去访问数组元素rainfall[counter]会触发类型不匹配的编译错误,这就是你遇到问题的根源。
修正后的代码(普通for循环版)
public static double determineLow(double[] rainfall) { // 先处理空数组/空指针的情况,让方法更健壮 if (rainfall == null || rainfall.length == 0) { throw new IllegalArgumentException("Rainfall array can't be empty or null!"); } double lowest = rainfall[0]; // 把counter改成int类型,符合数组索引的要求 for (int counter = 0; counter < rainfall.length; counter++) { if (rainfall[counter] < lowest) { lowest = rainfall[counter]; } } return lowest; }
更简洁的增强for循环版
如果你觉得普通for循环的索引写法麻烦,也可以用增强for循环直接遍历数组元素,代码更清爽:
public static double determineLow(double[] rainfall) { if (rainfall == null || rainfall.length == 0) { throw new IllegalArgumentException("Rainfall array can't be empty or null!"); } double lowest = rainfall[0]; for (double currentRain : rainfall) { if (currentRain < lowest) { lowest = currentRain; } } return lowest; }
额外说明
我还加了数组非空判断,避免当传入空数组或者null时出现数组越界或空指针异常,让你的方法更健壮可靠~
内容的提问来源于stack exchange,提问作者llamagish
相关产品推荐
相关产品推荐

