Java中Scanner读取输入存入ArrayList时的跳读问题求助
Scanner输入异常与ArrayList数据存储问题解决
问题根源分析
sc.nextInt()读取整数后,会把输入末尾的换行符留在输入缓冲区中,后续的sc.nextLine()会直接读取这个空换行符,导致跳过用户输入。- 使用
sc.next()只能读取空格前的内容,无法处理含空格的姓名、地址,不符合需求。 - 循环中重复使用同一个
Cliente clie对象,添加到ArrayList的所有元素都会指向同一个实例,最终所有客户数据会被最后一次输入覆盖。
具体修复步骤
- 清除换行符残留:在
int n = sc.nextInt();之后,添加sc.nextLine();,吃掉缓冲区里的换行符,确保后续nextLine()能正确读取用户输入。 - 每次循环新建Cliente实例:把
Cliente clie = new Cliente();移到for循环内部,每次循环创建新对象,避免数据覆盖。 - 统一使用nextLine()读取文本:所有需要读取含空格的输入(姓名、地址)都用
nextLine(),金额用nextDouble(),之后同样处理换行符(如果后续还有nextLine())。 - 补充金额读取逻辑:按照需求添加金额(credito)的输入步骤,并正确赋值给Cliente对象。
修改后的完整代码
Main类代码
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); List<Cliente> lista = new ArrayList<Cliente>(); System.out.println("Ingrese la cantidad de clientes a ingresar: "); int n = sc.nextInt(); sc.nextLine(); // 吃掉nextInt()残留的换行符 for (int i = 0; i < n; i++) { Cliente clie = new Cliente(); // 每次循环新建Cliente对象 System.out.println("Al cliente se le asignó el número de cliente: " + i); clie.setCodigoCliente(i); System.out.println("Ingrese el nombre del cliente " + i); String nom = sc.nextLine(); clie.setNombre(nom); System.out.println("Ingrese la dirección del cliente " + i); String direccion = sc.nextLine(); clie.setDireccion(direccion); System.out.println("Ingrese el monto de crédito del cliente " + i); double credito = sc.nextDouble(); sc.nextLine(); // 吃掉nextDouble()残留的换行符 clie.setCredito(credito); lista.add(clie); // 将当前客户对象添加到集合 } // 可选:验证集合中的数据 System.out.println("\nLista de clientes ingresados:"); for (Cliente cliente : lista) { System.out.printf("Cliente %d: Nombre=%s, Dirección=%s, Crédito=%.2f%n", cliente.getCodigoCliente(), cliente.getNombre(), cliente.getDireccion(), cliente.getCredito()); } sc.close(); } }
Cliente类代码(补全getter/setter)
public class Cliente { int codCliente; String nombre; String direccion; double credito; public Cliente() { } public Cliente(String nombre, String direccion, double credito) { this.nombre = nombre; this.direccion = direccion; this.credito = credito; } // 补全getter和setter方法 public int getCodigoCliente() { return codCliente; } public void setCodigoCliente(int codCliente) { this.codCliente = codCliente; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getDireccion() { return direccion; } public void setDireccion(String direccion) { this.direccion = direccion; } public double getCredito() { return credito; } public void setCredito(double credito) { this.credito = credito; } }
关键修改说明
- 换行符处理:每次使用
nextInt()/nextDouble()等读取非字符串类型后,必须调用nextLine()清除缓冲区的换行,否则后续nextLine()会读取空内容。 - 对象实例化位置:将Cliente对象的创建放在循环内部,确保每个客户数据都存储在独立的对象中,避免集合中所有元素指向同一个实例。
- 输入方法选择:使用
nextLine()处理所有含空格的文本输入,保证姓名、地址等带空格的内容能被完整读取。
内容的提问来源于stack exchange,提问作者Nicolas Ramos
相关产品推荐
相关产品推荐

