Java程序提取输入整数序列前两大数时第二高值计算错误求助
问题根因
你的第二高值统计逻辑存在核心错误,直接导致结果不符合预期:
- 初始值设置错误:
second初始值设为Integer.MAX_VALUE(即int类型最大值2147483647),正常用户输入的整数都不会超过这个值,导致更新第二高的判断分支永远不会触发,second一直停在初始值 - 第二高更新逻辑缺失:当新的最大值出现时,原来的最大值应该自动成为新的第二高,你的代码完全没有处理这个场景
- 计数逻辑完全混乱:只要输入值小于当前第一高就给第二高计数,根本没有判断输入值是否等于当前第二高,累加的计数完全没有意义
- 冗余代码:定义了
max、min两个变量但全程没有使用,属于无效代码
修复方案
遍历每个输入整数时,按优先级分层判断即可:
- 如果当前数大于已记录的第一高值:将原第一高值和对应计数平移给第二高,再把当前数设为新的第一高,计数重置为1
- 如果当前数等于第一高值:直接给第一高的计数加1
- 如果当前数小于第一高,但大于已记录的第二高值:将当前数设为新的第二高,计数重置为1
- 如果当前数等于第二高值:直接给第二高的计数加1
- 其余比第二高小的数直接跳过,不做处理
注意:第一高、第二高的初始值都要设为Integer.MIN_VALUE(int类型最小值),保证第一个输入的数能正常触发更新逻辑。
修复后的完整可运行代码:
import java.util.Scanner; public class TopTwo { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter a sequence of numbers: "); int first = Integer.MIN_VALUE; int firstOccurrences = 0; int second = Integer.MIN_VALUE; int secondOccurrences = 0; while(input.hasNextInt()){ int x = input.nextInt(); if (x > first) { // 原最大值降级为第二高 second = first; secondOccurrences = firstOccurrences; // 更新最大值 first = x; firstOccurrences = 1; } else if (x == first) { firstOccurrences++; } else if (x > second) { // 更新第二高 second = x; secondOccurrences = 1; } else if (x == second) { secondOccurrences++; } } input.close(); System.out.println("The highest is " + first + ". Its number of occurrences is " + firstOccurrences); System.out.println("The second highest is " + second + ". Its number of occurrences is " + secondOccurrences); } }
验证结果
用给出的测试用例验证:依次输入24、56、62、12、79、-19、-12、-5、5,最后输入fin终止输入,程序输出如下:
The highest is 79. Its number of occurrences is 1
The second highest is 62. Its number of occurrences is 1
结果完全符合预期。
内容的提问来源于stack exchange,提问作者user19382080
相关产品推荐
相关产品推荐

