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

Java使用Scanner输入时nextLine无法接收第二个值跳过逻辑问题求助

问题根源

你的代码问题出在Scanner类的输入读取逻辑上:

  • scan.nextInt() 只会读取输入流中的整数内容,你输入宾客数后按下的换行符\n会残留在输入缓冲区中
  • 后续执行scan.nextLine()时,会直接读取到这个残留的换行符,判定为一行空内容,因此不会等待你输入房型,直接给dRoomType赋值为空字符串,最终触发了else分支逻辑返回404号房。
修复方案

有两种常用修复方式:

方案1:手动消耗残留换行符

在scan.nextInt()之后加一行空的nextLine()吃掉缓冲区里的换行符:

System.out.print("Enter the number of guests: ");
int guestNos = scan.nextInt();
// 新增这行,消耗nextInt残留的换行符
scan.nextLine();

System.out.print("Enter the desired type of room: ");
String dRoomType = scan.nextLine();

方案2:统一使用nextLine()读取后做类型转换

所有输入都用nextLine()读取,需要数值类型时自行转换,避免不同读取方法的兼容问题:

System.out.print("Enter the number of guests: ");
int guestNos = Integer.parseInt(scan.nextLine());

System.out.print("Enter the desired type of room: ");
String dRoomType = scan.nextLine();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 16:54:03