Java Scanner类nextLine()异常:输入姓名后自动进入下一个do-while校验循环
问题根源
你的代码存在两个核心逻辑错误,和第一个姓名校验的循环无关:
- 年龄校验的
else if判断中连续调用了两次scanner.nextInt():- 短路或
||的特性是前半段条件成立时不会执行后半段代码,你输入的年龄小于等于3时,第二个nextInt()不会触发; - 当输入的年龄大于3时,程序会执行第二个
nextInt(),尝试读取新的整数输入,和你要校验当前输入的逻辑完全不符。
- 短路或
- 输入不是整数的错误分支中,没有消费掉当前行的无效输入,导致无效内容一直残留在缓冲区,下次循环会重复读到同样的内容,进入死循环。
修复方案
调整年龄校验的循环逻辑,先把整数读取到临时变量再做校验,所有错误分支都清空当前行残留的输入:
String name = ""; boolean flag_name= false; do{ System.out.print("Name: "); if(scanner.hasNextInt()){ System.out.println(scanner.nextInt() + " That's not a valid name...\n"); scanner.nextLine(); }else{ name = scanner.nextLine(); flag_name = true; } }while(!flag_name); int age = 0; boolean good_age = false; do { System.out.print("Age: "); if (!scanner.hasNextInt()){ System.out.println("That's not a valid age."); // 新增:消费掉当前行的无效输入 scanner.nextLine(); }else { // 先把整数读出来存到临时变量,不要重复调用nextInt() int inputAge = scanner.nextInt(); if(inputAge <= 3 || inputAge >= 125) { System.out.println("You must be over 3yo."); scanner.nextLine(); }else{ age = inputAge; // 消费掉整数后的换行符,避免影响后续输入 scanner.nextLine(); good_age = true; } } }while (!good_age);
内容的提问来源于stack exchange,提问作者Alejandro Martinez
相关产品推荐
相关产品推荐

