You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何向ArrayList添加一个对象后while循环提前终止?

问题分析与修复

问题根源

使用scanner.nextInt()读取节目时长后,输入缓冲区中会残留一个换行符(由按下回车产生)。当下一次循环执行scanner.nextLine()读取节目名称时,会直接读取到这个空的换行符,触发programName.isEmpty()的判断,导致循环提前终止。

修复方案

有两种简单的修复方式:

方式一:消耗残留的换行符

在调用scanner.nextInt()后,额外调用一次scanner.nextLine()来清空输入缓冲区里的换行符:

import java.util.ArrayList;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        ArrayList<TelevisionProgram> programs = new ArrayList<>();
        Scanner scanner = new Scanner(System.in);

        while (true) {
            System.out.print("Name: ");
            String programName = scanner.nextLine();
            if (programName.isEmpty()) {
                break;
            }
            System.out.print("Duration: ");
            int durationOfProgram = scanner.nextInt();
            // 消耗掉nextInt()后残留的换行符
            scanner.nextLine();
            programs.add(new TelevisionProgram(programName, durationOfProgram));
        }
        System.out.println();
        System.out.print("Program's maximum duration? ");
        int maxDuration = scanner.nextInt();
        for (TelevisionProgram show : programs) {
            if (show.getDuration() <= maxDuration) {
                System.out.println(show);
            }
        }
    }
}

方式二:统一使用nextLine()读取输入

所有输入都用scanner.nextLine()读取,再将时长的字符串转换为整数,避免缓冲区残留问题:

import java.util.ArrayList;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        ArrayList<TelevisionProgram> programs = new ArrayList<>();
        Scanner scanner = new Scanner(System.in);

        while (true) {
            System.out.print("Name: ");
            String programName = scanner.nextLine();
            if (programName.isEmpty()) {
                break;
            }
            System.out.print("Duration: ");
            // 读取整行后转换为整数
            int durationOfProgram = Integer.parseInt(scanner.nextLine());
            programs.add(new TelevisionProgram(programName, durationOfProgram));
        }
        System.out.println();
        System.out.print("Program's maximum duration? ");
        int maxDuration = Integer.parseInt(scanner.nextLine());
        for (TelevisionProgram show : programs) {
            if (show.getDuration() <= maxDuration) {
                System.out.println(show);
            }
        }
    }
}

内容的提问来源于stack exchange,提问作者Alex Roman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 21:06:24