尽管我得到结果,但为什么仍然出现此错误?

在下面的代码中获取异常:

import java.io.*;

public static void main(String[] args) throws IOException{
    FileReader objRead = new FileReader("/home/acer/Desktop/sulabh");
    BufferedReader objB = new BufferedReader(objRead);
    String input = null;
    while((input=objB.readLine())!= null){
        String temp = input.substring(0,2);
       if(temp.contains("77")) {
           System.out.println(input);
       }
    }
    objB.close();
}

答案的错误是:
777
777

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 0,end 2,length 0 at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3319) at java.base/java.lang.String.substring(String.java:1874) at Main.main(Main.java:10)
yin3573389 回答:尽管我得到结果,但为什么仍然出现此错误?

从Java文档中获取子字符串:

Throws:
    IndexOutOfBoundsException - if the beginIndex is negative,or endIndex is larger than the length of this String object,or beginIndex is larger than endIndex.

您的String temp = input.substring(0,2);在获得两条好线后得到的行长小于长度2。

对此进行保护。

String temp = "";

if (input.length()>=2){
temp = input.substring(0,2);
}
,

我猜前两行已经处理妥当了,它在最后的空白行引发了错误。请检查文件末尾是否有空白行。空行可能包含少于2个chracters。

或者,您也可以尝试input.startsWith("77")

本文链接:https://www.f2er.com/3017342.html

大家都在问