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
相关产品推荐
相关产品推荐

