Java Eclipse中Customer类程序Scanner跳过街道地址输入行求助
解决Scanner输入时跳过街道地址的问题
这个问题我太熟悉了——这是Java Scanner类的一个常见坑!问题出在scan.nextInt()这个方法上:它只会读取输入的整数部分,不会处理你输入年龄后按下的回车键(也就是换行符\n)。这个残留的换行符会留在输入缓冲区里,当程序执行到actualCustomer.setStreetAddress(scan.nextLine());时,nextLine()会直接读取这个空的换行符,导致看起来像是跳过了街道地址的输入。
给你两个简单的解决方案,选哪个都可以:
方案1:消耗掉残留的换行符
在调用nextInt()之后,额外调用一次scan.nextLine()来吃掉那个多余的换行符:
System.out.println("Enter your age: "); actualCustomer.setAge(scan.nextInt()); // 新增这一行,消耗掉nextInt()留下的换行符 scan.nextLine();
修改后的完整main方法代码:
//main method public static void main(String[] args) { Scanner scan = new Scanner(System.in); Customer actualCustomer = new Customer(); System.out.println("Enter your name: "); actualCustomer.setName(scan.nextLine()); System.out.println("Enter your age: "); actualCustomer.setAge(scan.nextInt()); // 处理换行符残留 scan.nextLine(); System.out.println("Enter your street address: "); actualCustomer.setStreetAddress(scan.nextLine()); System.out.println("Enter the city you live in: "); actualCustomer.setCity(scan.nextLine()); System.out.println("Enter the state you live in: "); actualCustomer.setState(scan.nextLine()); System.out.println("Enter your zip code: "); actualCustomer.setZip(scan.nextLine()); System.out.println(actualCustomer.displayAddressLabel()); System.out.println(actualCustomer.displayAddress()); }
方案2:统一用nextLine()读取所有输入(更推荐)
为了避免这类换行符问题,你可以统一用scan.nextLine()读取所有输入,然后把年龄的字符串转换成int类型。这样整个输入流程会更一致,也不会有残留字符的问题:
//main method public static void main(String[] args) { Scanner scan = new Scanner(System.in); Customer actualCustomer = new Customer(); System.out.println("Enter your name: "); actualCustomer.setName(scan.nextLine()); System.out.println("Enter your age: "); // 先读取字符串,再转成int int age = Integer.parseInt(scan.nextLine()); actualCustomer.setAge(age); System.out.println("Enter your street address: "); actualCustomer.setStreetAddress(scan.nextLine()); System.out.println("Enter the city you live in: "); actualCustomer.setCity(scan.nextLine()); System.out.println("Enter the state you live in: "); actualCustomer.setState(scan.nextLine()); System.out.println("Enter your zip code: "); actualCustomer.setZip(scan.nextLine()); System.out.println(actualCustomer.displayAddressLabel()); System.out.println(actualCustomer.displayAddress()); }
两种方案都能解决你的问题,方案2更适合长期维护,因为它避免了混合使用不同Scanner方法带来的潜在问题。
内容的提问来源于stack exchange,提问作者Ryan Horner
相关产品推荐
相关产品推荐

