【问题标题】:StringIndexOutOfBoundsException Thrown [duplicate]抛出 StringIndexOutOfBoundsException [重复]
【发布时间】:2018-04-16 10:19:19
【问题描述】:

很抱歉,如果问题已经被问过,我刚刚收到了一个 "java.lang.StringIndexOutOfBoundsException",尽管我的程序在第一次尝试时运行正确。我试图更改我的子字符串的索引,但它也不起作用。这是抛出的完整异常:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 8, end 17, length 9
at java.base/java.lang.String.checkBoundsBeginEnd(Unknown Source)
at java.base/java.lang.String.substring(Unknown Source)
at platerecognition.PlateRecognition.main(PlateRecognition.java:31)

下面是几行:

public class Asserv {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws FileNotFoundException {

   final File folder = new File("./Verr");

   PrintWriter pw = new PrintWriter(new File("Gel.csv"));

   for (final File fileEntry : folder.listFiles()) {
    if (!fileEntry.isDirectory()) { 
        String filename = fileEntry.getName();
        String date = filename.substring(0, 8);
        System.out.println(date);
        String time = filename.substring(8,17);
        System.out.println(time);
        int index = filename.indexOf("_", 19);
        String plate = filename.substring(18,index);
        System.out.println(plate);        
        int index2 = filename.indexOf("-", index+2);
        String cam = filename.substring(index+4, index2);
        System.out.println(cam);
        String last = filename.substring(index2 + 1, filename.indexOf('.', index2 + 1));
        System.out.println(last);
        System.out.println(fileEntry.getName());

【问题讨论】:

  • filename 的值是多少?
  • 你能发布时间的价值吗?
  • 你的结束索引必须是
  • 请将代码放入问题中,而不是放入 cmets - 并显示实际值,而不仅仅是创建值的代码。
  • 抱歉,已经完成了

标签: java indexing parameters substring


【解决方案1】:

您可以阅读异常消息begin 8, end 17, length 9,如下所示:

您要求从 8(开始)到 17(结束)的 substring,但当前长度为 9。

来自String.substring

投掷:

IndexOutOfBoundsException - 如果 beginIndex 为负数,或 endIndex 大于此 String 对象的长度,或 beginIndex 大于 endIndex。

您需要检查String 的长度以防止出现此异常。类似的东西:

int begin = 8;
int end = 17;
s.substring(begin, Math.min(s.length(), end));

我使用Math.min(s.length(), end) 来获得最低值,它将是end 或此String 的限制。

注意:如果begin 大于end(或长度),这将是同样的问题。所以这并不完全安全,但你明白了。

这是一个快速的方法

public static String substring(String s, int begin, int end){
    //Prevent out of bounds by stopping at the end of the `String`
    end = Math.min(end, s.length());

    return s.substring(begin, end);
}

【讨论】:

  • 从 8 到 17 的子字符串的长度正好是 9,所以我认为它不会走得太远
  • 我相信length 是您调用Stringsubstring 的长度,而不是子字符串本身的长度。我不得不猜测,因为此消息取决于所使用的 JDK。但是String.substring 的文档非常明确。
  • 我调用子串的字符串的长度是20,也不算太远,我也不明白的是程序在第一次尝试时运行正常
  • 第一次尝试”@YacineWalid 是什么意思?
  • 我的意思是我第一次跑
猜你喜欢
  • 2019-08-30
  • 2019-06-20
  • 1970-01-01
  • 2014-09-14
  • 1970-01-01
  • 2021-06-17
  • 2016-05-21
  • 1970-01-01
相关资源
最近更新 更多