You need to enable JavaScript to run this app. Java开发:向ArrayList<Integer>存入Scanner读取的文件值时报类型不兼容错误
优惠活动
大模型
产品
解决方案
定价
更多

Java开发:向ArrayList<Integer>存入Scanner读取的文件值时报类型不兼容错误

编译错误根源
  • 报错直接原因:Scanner 类的 next() 方法返回值为字符串类型,而 keys 是泛型为 Integer 的 ArrayList,其 add() 方法仅接受 Integer 类型入参,直接传入字符串会触发类型不兼容的编译错误。
  • 代码附带的其他潜在问题:
    • 路径硬编码:Paths.get("dbName") 写死了字符串常量,未使用传入的参数 dbName,会导致实际读取的文件名和传入值不一致。
    • 空指针风险:IO异常捕获后未终止流程,后续 scan 为 null 时执行读取操作会直接抛出空指针异常。
    • 循环逻辑失效:循环条件 i < users.size() 依赖传入集合的大小,初始传入的空集合会让循环完全不执行,无法读取任何内容。
    • 资源泄漏:未关闭Scanner实例,会导致文件句柄长期占用。
修复方案
  1. 解决类型不兼容问题:将Scanner读取到的字符串手动转换为Integer类型再存入集合,使用Integer.parseInt()将字符串转为int,自动装箱为Integer即可符合泛型要求。
  2. 同步修正上述潜在逻辑问题:
    • 把硬编码的路径替换为传入的参数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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.26 03:06:04