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

Java使用Scanner类获取用户输入时导演与时长输入提示同时弹出问题

问题触发原因

这是Java Scanner 类的经典输入缓冲区残留问题:
nextInt() 方法仅会读取输入流中的整数内容,不会处理用户输入完数字按下回车产生的换行符,该换行符会一直残留在输入缓冲区中。当后续调用nextLine()方法时,nextLine()会直接读取到缓冲区中残留的空换行符,判定为一次输入完成,不会等待用户手动输入导演字段内容,因此会出现时长、导演的输入提示同时打印的现象。

解决方案

有三种常用的修复方案,可根据场景选择:

  • 方案1:每次调用nextInt()后,额外调用一次nextLine()手动消耗掉残留的换行符,修改后代码如下:
System.out.println("Enter the title: ");
String title = myObj.nextLine();

System.out.println("Enter the year: ");
int year = myObj.nextInt();
myObj.nextLine(); // 清除年份输入残留的换行符

System.out.println("Enter the duration: ");
int duration = myObj.nextInt();
myObj.nextLine(); // 清除时长输入残留的换行符

System.out.println("Enter the director: ");
String director = myObj.nextLine();

System.out.println("Enter the actors: ");
String actors  = myObj.nextLine();

System.out.println("Enter the genre: ");
String genre = myObj.nextLine();
int rating = ran.nextInt(10) + 1;
  • 方案2:所有输入统一使用nextLine()接收,再手动转换为对应数据类型,从根源避免换行符残留问题,适合所有输入场景:
    比如读取年份的逻辑改为:int year = Integer.parseInt(myObj.nextLine());,读取时长的逻辑改为:int duration = Integer.parseInt(myObj.nextLine());
  • 方案3:将接收字符串的nextLine()替换为next(),仅适用于输入内容不含空格的场景,导演、演员这类可能携带空格的字段不推荐使用该方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 17:54:03