Java使用Scanner输入做数组重复校验时出现无限循环问题
代码触发无限循环的原因
- Scanner输入缓冲区残留换行符
al.nextInt()仅读取输入的整数数值,不会处理输入完成后按下回车产生的换行符。后续首次执行al.nextLine()时会直接读取到该残留换行,得到空字符串,导致首条姓名录入为空。 - 字符串比较逻辑错误
Java中==用于比较对象的内存地址而非内容,正常录入的相同内容字符串会因为是不同对象被==判定为不相等,去重逻辑失效;而多次读取到的空字符串是同一个常量对象,==会持续判定为相等,每次都执行i--让循环变量无法递增,最终触发无限循环。
修复方案
按以下步骤调整代码即可:
- 调用完
nextInt()后新增一行al.nextLine(),主动消费残留的换行符 - 将字符串比较逻辑从
list[i] == list[j]替换为list[i].equals(list[j]),如果要避免空指针风险可以用java.util.Objects.equals(list[i], list[j]) - 检测到姓名重复后直接跳出内层循环,避免无效遍历
修复后完整代码
import java.util.Objects; import java.util.Scanner; public class NameList { public static void main(String[] args) { int numberofhumans; Scanner al = new Scanner(System.in); System.out.print("Enter the number of person: "); numberofhumans = al.nextInt(); // 消费nextInt残留的换行符 al.nextLine(); String[] list = new String[numberofhumans]; for (int i = 0; i < numberofhumans; i++) { System.out.print("Enter the name:"); list[i] = al.nextLine(); boolean duplicate = false; for (int j = 0; j < i; j++) { // 用Objects.equals比较字符串内容,避免空指针 if (Objects.equals(list[i], list[j])) { duplicate = true; break; } } if (duplicate) { System.out.println("Name you just typed is already in your list. Enter a different name."); i--; } } for (String string : list) { System.out.println(string); } al.close(); } }
内容的提问来源于stack exchange,提问作者TarikTEM
相关产品推荐
相关产品推荐

