Java Scanner输入异常:程序未等待姓名输入直接执行后续逻辑
修复Scanner输入跳过姓名的问题
这个问题我太熟悉了——这是Scanner类的经典“换行符残留”坑,咱们一步步说清楚原因和解决办法:
问题根源
当你用keyboard.nextInt()读取选择的数字时,它只会读取输入的整数部分,不会消耗掉输入末尾的换行符(就是你按回车的那个字符)。接下来调用keyboard.nextLine()时,它会直接读取这个剩下的换行符,把它当成一个空的输入,所以程序直接跳过了姓名输入,直奔出生日期的环节。
解决方案1:手动消耗换行符
在nextInt()之后,额外调用一次keyboard.nextLine()来吃掉残留的换行符,修改后的完整代码如下:
import java.util.Scanner; public class Person { public static void main(String[] args){ Person p1 = new Person(); System.out.println("1: Add Person"); System.out.println("2: Delete Person"); System.out.println(); System.out.print("Please make a selection: "); Scanner keyboard = new Scanner(System.in); int selection = keyboard.nextInt(); // 消耗掉nextInt()留下的换行符 keyboard.nextLine(); switch(selection){ case 1: System.out.print("Please enter name: "); String name = keyboard.nextLine(); p1.addPerson(name, keyboard); break; } } public Person(){ } public void addPerson(String name, Scanner keyboard){ int day, month, year; System.out.print("Please enter date of birth in the format dd mm yyyy: "); day = keyboard.nextInt(); month = keyboard.nextInt(); year = keyboard.nextInt(); } }
解决方案2:统一用nextLine读取后转换
另一种更稳妥的方式是全程用nextLine()读取输入,再把需要整数的部分转换成int,从根源上避免换行符问题:
// 替换main方法里的选择读取部分 System.out.print("Please make a selection: "); String selectionStr = keyboard.nextLine(); int selection = Integer.parseInt(selectionStr);
额外优化建议
你在addPerson方法里又新建了一个Scanner对象,这完全没必要,还可能导致输入流混乱。整个程序只需要一个Scanner实例,把它作为参数传递给addPerson方法就好(就像上面代码里改的那样),这样能避免多个Scanner争抢输入流的问题。
现在运行修改后的程序,就能正常等待你输入姓名啦!
内容的提问来源于stack exchange,提问作者chad
相关产品推荐
相关产品推荐

