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

DO WHILE循环执行后Scanner无法工作的技术求助

解决Scanner在nextInt()后nextLine()无法正常读取输入的问题

嘿,我完全懂你遇到的问题——当你输入1选择继续录入新记录后,程序直接跳过了staffID和password的输入环节,对吧?这是Scanner类的输入缓冲区遗留换行符导致的典型问题。

问题原因

当你用input.nextInt()读取整数时,它只会读取输入的数字部分,而你按下回车键产生的换行符\n会留在输入缓冲区里。接下来调用input.nextLine()的时候,它会直接读取这个遗留的换行符,相当于读取了一个空字符串,所以看起来像是“跳过了输入”,实际上是Scanner已经“读了东西”,只是这个东西是空的而已。

解决方案

这里有两种常用的解决办法,你可以根据需求选择:

方法1:在nextInt()后额外调用一次nextLine()清空缓冲区

这是最简单直接的方式,在读取完整数后,用一次input.nextLine()把缓冲区里的换行符吃掉:

a = input.nextInt();
input.nextLine(); // 关键:清空遗留的换行符

修改后的完整代码如下(顺便帮你补上了staffCount++,不然每次循环都会覆盖同一个数组元素,之前的记录会丢失哦):

public class Test { 
    public static void main(String args[]){ 
        String staffID, staffPassword; 
        int a = 0; 
        boolean validation; 
        Staff[] staff = new Staff[1000]; 
        int staffCount = 0; 
        Scanner input = new Scanner(System.in); 
        do{ 
            staff[staffCount] = new Staff(); 
            System.out.print("Staff ID: "); 
            staffID = input.nextLine(); 
            staff[staffCount].SetStaffID(staffID); 
            System.out.print("Password: "); 
            staffPassword = input.nextLine(); 
            staff[staffCount].SetPassword(staffPassword); 
            System.out.println("\nEnter 1 to continue, enter 2 to stop."); 
            System.out.print("Continue to add more record?(1 or 0): " ); 
            a = input.nextInt(); 
            input.nextLine(); // 清空缓冲区的换行符
            staffCount++; // 新增:让数组索引递增,避免覆盖之前的记录
        }while(a == 1); 
    } 
}

方法2:全程用nextLine()读取,再转换为整数(更健壮)

如果你想避免缓冲区问题,同时处理用户输入非整数的情况(比如用户输了字母),可以全程用nextLine()读取输入,再把字符串转换成整数:

// 替换原来的a = input.nextInt();部分
System.out.print("Continue to add more record?(1 or 0): " );
String inputStr = input.nextLine();
try {
    a = Integer.parseInt(inputStr);
} catch (NumberFormatException e) {
    // 处理输入无效的情况
    System.out.println("请输入有效的数字(1或0)!");
    a = 1; // 让循环继续,提示用户重新输入
}

这种方法更灵活,能避免因用户输入错误导致程序崩溃。

内容的提问来源于stack exchange,提问作者LAI SHUN KEAT

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 14:32:35