Java Scanner读取异常及最大数统计程序逻辑问题求助
问题排查与修正:读取数字序列统计最大值及出现次数
核心问题:重复调用scanner.nextInt()搞乱了输入读取
你这段代码里,while循环条件、if判断、else if判断里都在调用scanner.nextInt()——每次调用这个方法,都会从输入流里读走一个新数字。这就导致一次循环里会跳过好几个输入值,要么程序卡在等输入的状态(因为输入流里的数字被提前读完了),要么统计的最大值和次数完全不对。比如你测试输入2 3 9 4 5 9 3 3 0时,循环条件先读2,接着if里读3,比较后又读9赋值给max,直接跳过了中间的数字,逻辑完全跑偏。
修正后的代码
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter numbers, input ends with 0: "); int max = Integer.MIN_VALUE; // 初始值设为最小整数,能处理全负数的输入情况 int count = 0; int currentNum; // 先把当前数字读出来存到变量里,后续判断都用这个变量 while ((currentNum = scanner.nextInt()) != 0) { if (currentNum > max) { max = currentNum; count = 1; } else if (currentNum == max) { count++; } } // 判断是否只输入了0 if (max == Integer.MIN_VALUE) { System.out.println("No numbers are entered except zero."); } else { System.out.println("The largest number is " + max); System.out.println("The occurence count of the largest number is " + count); } scanner.close(); // 用完记得关闭Scanner释放资源 } }
关键修正点说明
- 单次读取,复用变量:在while循环里一次性把数字读到
currentNum里,所有判断都基于这个变量,不会再乱读输入。 - 优化初始值:原来把max设为0,如果输入的全是负数,统计出来的最大值会是0,完全错误。改成
Integer.MIN_VALUE就能适配所有整数输入场景。 - 修正空输入判断:只有输入0的情况下,max会保持
Integer.MIN_VALUE,用这个判断更准确。 - 添加资源释放:用完Scanner后关闭它,养成好的编程习惯。
内容的提问来源于stack exchange,提问作者Chandler Smith
相关产品推荐
相关产品推荐

