Java开发:向ArrayList<Integer>存入Scanner读取的文件值时报类型不兼容错误
编译错误根源
- 报错直接原因:
Scanner类的next()方法返回值为字符串类型,而keys是泛型为Integer的ArrayList,其add()方法仅接受Integer类型入参,直接传入字符串会触发类型不兼容的编译错误。 - 代码附带的其他潜在问题:
- 路径硬编码:
Paths.get("dbName")写死了字符串常量,未使用传入的参数dbName,会导致实际读取的文件名和传入值不一致。 - 空指针风险:IO异常捕获后未终止流程,后续
scan为null时执行读取操作会直接抛出空指针异常。 - 循环逻辑失效:循环条件
i < users.size()依赖传入集合的大小,初始传入的空集合会让循环完全不执行,无法读取任何内容。 - 资源泄漏:未关闭Scanner实例,会导致文件句柄长期占用。
- 路径硬编码:
修复方案
- 解决类型不兼容问题:将Scanner读取到的字符串手动转换为Integer类型再存入集合,使用
Integer.parseInt()将字符串转为int,自动装箱为Integer即可符合泛型要求。 - 同步修正上述潜在逻辑问题:
- 把硬编码的路径替换为传入的参数
dbName - IO异常捕获后直接退出方法,避免空指针
- 改用
Scanner.hasNext()作为循环判断条件,只要文件还有未读取的内容就持续读取 - 补充Scanner的资源关闭操作
- 把硬编码的路径替换为传入的参数
修正后的完整代码如下:
/** * readFromFile method will read from the database file and save all usernames, * passwords, and keys in the corresponding ArrayLists.If the file cannot open, * output error message: <dbName> cannot open! * @param dbName The file name to save all users, passwords, and keys * @param users * @param pwds * @param keys */ public static void readFromFile(String dbName, ArrayList<String> users, ArrayList<String> pwds, ArrayList<Integer> keys) { Path path = Paths.get(dbName); Scanner scan = null; try { scan = new Scanner(path); } catch (IOException e) { System.out.println(dbName + " cannot open!"); return; } while (scan.hasNext()) { users.add(scan.next()); pwds.add(scan.next()); keys.add(Integer.parseInt(scan.next())); } scan.close(); }
注意:如果文件中存储的密钥不是纯数字格式,
Integer.parseInt()会抛出NumberFormatException,可根据业务需要补充对应异常捕获逻辑。
内容的提问来源于stack exchange,提问作者DikDikee
相关产品推荐
相关产品推荐

