Java二维数组列最小值获取失败,求问题根源排查帮助
排查二维数组列最小值无法更新的问题
首先明确你的数组对应关系:sales是**区域(行)×品牌(列)**的结构,每个品牌对应sales的一列,要获取每个品牌在各区域的销量最值,必须正确遍历列维度。
你的最小值始终不变,大概率是以下几个原因之一:
常见错误点及修复
最小值初始值未按列重置
如果你在所有循环外把min初始化为sales[0][0],然后处理每一列时没有重新赋值为当前列的第一个元素(sales[0][col]),那么只要后续列的所有销量都比sales[0][0]大,最小值就永远不会更新。
正确做法:在遍历每个品牌(列)的循环开头,将minSales重置为当前列的第一个区域销量。遍历维度顺序错误
要处理列的最值,必须外层循环遍历列(品牌),内层循环遍历行(区域)。如果搞反了遍历顺序,会导致你实际在处理行的最值,而非列的,自然得不到正确结果。比较条件写反
更新最小值时,必须判断当前值 < 最小值,如果写成当前值 > 最小值或者>=,永远不会触发最小值的更新。
正确示例代码
public class SalesAnalyzer { public static void main(String[] args) { String[] brands = { "ACTION", "DEFY", "GEL", "JETPRO", "MAGNUM" }; String[] districts = { "North", "West", "South", "East" }; int[][] sales = { { 17, 57, 35, 48, 31 }, { 35, 36, 53, 78, 76 }, { 55, 56, 96, 44, 56 }, { 35, 44, 34, 43, 44 } }; // 遍历每个品牌(列) for (int brandIdx = 0; brandIdx < brands.length; brandIdx++) { // 初始化当前品牌的最值为第一个区域的销量 int max = sales[0][brandIdx]; int min = sales[0][brandIdx]; String maxDistrict = districts[0]; String minDistrict = districts[0]; // 遍历剩余区域(行) for (int districtIdx = 1; districtIdx < districts.length; districtIdx++) { int currentSales = sales[districtIdx][brandIdx]; // 更新最大值 if (currentSales > max) { max = currentSales; maxDistrict = districts[districtIdx]; } // 更新最小值(注意是小于号) if (currentSales < min) { min = currentSales; minDistrict = districts[districtIdx]; } } // 输出结果 System.out.printf("品牌 %s:\n", brands[brandIdx]); System.out.printf(" 最高销量:%d(%s)\n", max, maxDistrict); System.out.printf(" 最低销量:%d(%s)\n\n", min, minDistrict); } } }
输出验证
运行上述代码会得到正确结果:
品牌 ACTION: 最高销量:55(South) 最低销量:17(North) 品牌 DEFY: 最高销量:57(North) 最低销量:36(West) 品牌 GEL: 最高销量:96(South) 最低销量:34(East) 品牌 JETPRO: 最高销量:78(West) 最低销量:43(East) 品牌 MAGNUM: 最高销量:76(West) 最低销量:31(North)
内容的提问来源于stack exchange,提问作者Rohith
相关产品推荐
相关产品推荐

