Java查找温度数组最大值对应月份的代码报错解决方案
问题
编写Java程序实现:匹配月份数组month与温度数组temp,输出最高温度对应的月份及温度值,现有代码运行无法得到正确结果,原始代码如下:
import java.util.Arrays; public class FindLargests { public static void main(String[] args) { //This defines the arrays String[] month = {"Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sep", "Oct", "Nov", "Dec"}; int[] temp = {34,32,40,50,55,70,73,75,70,65,55,40}; //For loop to search the temps array to find the largest value int max = temp[0]; int maxIndex = -1; for (int i = 0; i < temp.length; i++) { // i --> index if(temp[i]>max) max = temp[i]; } //This prints out the result System.out.print("The largest value is: " + month(i) + " - " + max); } }
错误点说明
代码共有两处直接导致编译失败/结果错误的问题:
- 遍历温度数组更新最大值时,没有同步更新最大值对应的索引变量
maxIndex,最终无法匹配到正确的月份 - Java数组元素访问需要使用方括号
[]语法,代码中写month(i)是方法调用的写法,会直接触发编译错误,且括号内也没有传入正确的最大值索引
修复后代码
public class FindLargests { public static void main(String[] args) { String[] month = {"Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sep", "Oct", "Nov", "Dec"}; int[] temp = {34,32,40,50,55,70,73,75,70,65,55,40}; int max = temp[0]; int maxIndex = 0; for (int i = 1; i < temp.length; i++) { if (temp[i] > max) { max = temp[i]; maxIndex = i; } } System.out.print("The largest value is: " + month[maxIndex] + " - " + max); } }
注:原始代码中导入的
java.util.Arrays没有被使用,已直接移除;初始最大值取数组第一个元素,因此maxIndex初始值设为0,遍历从索引1开始即可,减少一次无意义的比较。
运行结果
The largest value is: Aug - 75
内容的提问来源于stack exchange,提问作者purpledot
相关产品推荐
相关产品推荐

