【问题标题】:Why am I getting this error, eventhough I am getting result?为什么我得到这个错误,即使我得到了结果?
【发布时间】:2019-11-28 03:01:16
【问题描述】:

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

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)

【问题讨论】:

  • 使用System.out.println(input) 测试您实际阅读的内容
  • 你的输入文件是什么

标签: java substring runtime-error runtimeexception stringindexoutofbounds


【解决方案1】:

来自子字符串的 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);
}

【讨论】:

  • 或者去掉 temp 说 if (input.indexOf("77")==0)
【解决方案2】:

我猜前两行处理得很好,最后的空行会报错。请检查文件末尾是否有空行。空行可能包含少于 2 个字符。

你也可以试试input.startsWith("77")

【讨论】:

    猜你喜欢
    • 2016-11-25
    • 2021-12-22
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 2023-01-12
    • 1970-01-01
    • 2017-09-18
    • 2020-01-31
    相关资源
    最近更新 更多