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

Java入门问题:for-loop打印提示两次才接收字符串输入如何解决

Java Scanner输入异常问题解决方案

问题根因

  • 你调用Scanner.nextInt()方法时,只会读取输入的整数数值,不会处理输入完数字后按下回车键产生的换行符\n,该换行符会残留在输入缓冲区中
  • 第一次进入for循环调用input.nextLine()时,会直接读取到缓冲区残留的换行符,返回空字符串,所以数组第一个元素是空值,同时第一轮循环的输入逻辑直接走完,马上打印第二轮的输入提示,就出现了连续打印两次提示的现象

解决方法

方式1:调用nextInt()后加一次nextLine()消费残留的换行符

修改后的代码如下:

Scanner input = new Scanner(System.in);

System.out.print("Please enter the number of users: ");
int numUser = input.nextInt();
// 新增这一行,消费掉nextInt残留的换行符
input.nextLine();

String[] userArray = new String[numUser];


for (int i = 0; i < numUser; i++) {
    System.out.print("For user " + (i+1) + ", please type your username followed by enter: ");
    String inputUsername = input.nextLine(); 
    userArray[i] = inputUsername;
}
for (int i = 0; i < numUser; i++) {
    System.out.println(userArray[i]);
}

方式2:统一使用nextLine()读取输入,再自行转换数据类型

如果后续还有多种类型的输入场景,更推荐这种方式,避免频繁出现缓冲区残留的问题:

Scanner input = new Scanner(System.in);

System.out.print("Please enter the number of users: ");
// 直接用nextLine读整行,再转成int类型
int numUser = Integer.parseInt(input.nextLine());

String[] userArray = new String[numUser];


for (int i = 0; i < numUser; i++) {
    System.out.print("For user " + (i+1) + ", please type your username followed by enter: ");
    String inputUsername = input.nextLine(); 
    userArray[i] = inputUsername;
}
for (int i = 0; i < numUser; i++) {
    System.out.println(userArray[i]);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 06:57:04