如何将含字符串字段的对象传入ArrayList?解决name字段无法存入问题
问题原因
问题出在Scanner的输入处理逻辑上:sc.nextInt()只会读取数字部分,输入流中数字后的换行符会被留在缓冲区。原代码里的sc.next()不仅多余,还会干扰后续的sc.nextLine()——当你输入id后回车,sc.next()会跳过空白直到遇到有效字符,而sc.nextLine()则会直接读取当前行剩余的空内容,导致name变量为空,无法正确传入。
修复方案
这里提供三种可行的修复方式,你可以根据实际输入场景选择:
方案一:跳过换行符(推荐,支持姓名带空格)
移除多余的sc.next(),在sc.nextInt()后调用sc.nextLine()消费掉残留的换行符,再读取姓名:
public class NewClass { ArrayList<stu> m = new ArrayList<>(); private Scanner sc = new Scanner(System.in); public void add(){ int id = sc.nextInt(); sc.nextLine(); // 消费id输入后的换行符 String name = sc.nextLine(); m.add(new stu(id, name)); } public void printList(){ for(stu i : m){ System.out.println(i.getId() +" "+i.getName()); } } }
方案二:直接用next()读取姓名(仅支持无空格的姓名)
如果你的姓名不会包含空格,可以直接用sc.next()读取id后的姓名,不需要nextLine():
public class NewClass { ArrayList<stu> m = new ArrayList<>(); private Scanner sc = new Scanner(System.in); public void add(){ int id = sc.nextInt(); String name = sc.next(); // 直接读取空格分隔的姓名 m.add(new stu(id, name)); } public void printList(){ for(stu i : m){ System.out.println(i.getId() +" "+i.getName()); } } }
方案三:统一读取整行拆分(最灵活,支持任意格式输入)
通过sc.nextLine()读取整行输入,再拆分id和姓名,彻底避免Scanner的换行问题,还支持姓名带空格:
public class NewClass { ArrayList<stu> m = new ArrayList<>(); private Scanner sc = new Scanner(System.in); public void add(){ System.out.println("请输入id和姓名(空格分隔):"); String inputLine = sc.nextLine(); // 按第一个空格拆分,保留姓名中的空格 String[] inputParts = inputLine.split(" ", 2); int id = Integer.parseInt(inputParts[0]); String name = inputParts[1]; m.add(new stu(id, name)); } public void printList(){ for(stu i : m){ System.out.println(i.getId() +" "+i.getName()); } } }
内容的提问来源于stack exchange,提问作者Quangthaitran
相关产品推荐
相关产品推荐

