You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

读取文件字符串时charAt(1)抛出字符串过短异常的问题求助

问题

使用charAt()函数获取文件读取字符串的第一个和第二个字符时,执行charAt(0)正常,但charAt(1)抛出字符串过短异常,确认字符串长度足够。代码如下:

while(inputFile.hasNext()){
    //read file first line
    String line = inputFile.nextLine();
    //if the first 2 letters of the line the scanner is reading are the same
    //as the search letters print the line and add one to the linesPrinted count
    String lineOne = String.valueOf(line.charAt(0));
    String lineTwo = String.valueOf(line.charAt(1));
    String searchOne = String.valueOf(search.charAt(0));
    String searchTwo = String.valueOf(search.charAt(1));

    if (lineOne.compareToIgnoreCase(searchOne) == 0 && lineTwo.compareToIgnoreCase(searchTwo) == 0){
        System.out.println(line);
        linesPrinted++;
    }
}

已验证charAt(0)执行后字符串未被修改,移除charAt(1)相关代码后程序运行正常,确定是该代码引发问题。

解决方案

  • 优先做长度校验:文件中大概率存在空行或长度小于2的行(比如末尾空行、格式异常的行),哪怕你主观认为所有行都符合长度要求,也必须在调用charAt(1)前判断line.length() >= 2,避免数组越界:
    while(inputFile.hasNext()){
        String line = inputFile.nextLine();
        // 跳过长度不足2的行
        if(line.length() < 2){
            continue;
        }
        String lineOne = String.valueOf(line.charAt(0));
        String lineTwo = String.valueOf(line.charAt(1));
        String searchOne = String.valueOf(search.charAt(0));
        String searchTwo = String.valueOf(search.charAt(1));
    
        if (lineOne.compareToIgnoreCase(searchOne) == 0 && lineTwo.compareToIgnoreCase(searchTwo) == 0){
            System.out.println(line);
            linesPrinted++;
        }
    }
    
  • 简化字符比较逻辑:无需将字符转为字符串再比较,直接用Character.toLowerCase()统一大小写后对比,代码更简洁高效:
    while(inputFile.hasNext()){
        String line = inputFile.nextLine();
        if(line.length() < 2){
            continue;
        }
        char lineFirst = Character.toLowerCase(line.charAt(0));
        char lineSecond = Character.toLowerCase(line.charAt(1));
        char searchFirst = Character.toLowerCase(search.charAt(0));
        char searchSecond = Character.toLowerCase(search.charAt(1));
    
        if (lineFirst == searchFirst && lineSecond == searchSecond){
            System.out.println(line);
            linesPrinted++;
        }
    }
    
  • 检查search字符串的合法性:还要确认search字符串的长度至少为2,否则search.charAt(1)同样会抛出越界异常,建议在循环外先做一次校验:
    if(search == null || search.length() < 2){
        // 处理search字符串不合法的情况,比如抛出异常或直接返回
        throw new IllegalArgumentException("search字符串长度必须至少为2");
    }
    

内容的提问来源于stack exchange,提问作者Max4

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 21:45:34