【问题标题】:String Index Out of Bounds Exception in Java [duplicate]Java中的字符串索引越界异常[重复]
【发布时间】:2017-09-07 03:00:45
【问题描述】:

这是我应该解析的输入:#typ offer; #det 免费基本用品 4 只疏散宠物。 #loc 2323 第 55 街,博尔德; #lat 40.022;

这是我的代码: System.out.print("输入正确格式的推文:"); String tweet = keyboard.nextLine();

    int start = tweet.indexOf("#");
    int finish = tweet.indexOf(";");
    String type = tweet.substring(start, finish);
    String type2 = type.substring(4,finish);
    String type_2 = type2.toUpperCase();



    String tweet2 = tweet.substring(finish + 1);
    int start2 = tweet2.indexOf("#");
    int finish2 = tweet2.indexOf(";");
    String detail = tweet2.substring(start2, finish2);
    String detail2 = tweet2.substring(5, finish2);



    String tweet3 = tweet2.substring(finish2 + 1);
    int start3 = tweet3.indexOf("#");
    int finish3 = tweet3.indexOf(";");
    String location = tweet3.substring(start3 , finish3);
    String location2 = tweet3.substring(4, finish3);

    /*
    String tweet4 = tweet3.substring(finish3 + 1);
    int start4 = tweet4.indexOf("#");
    int finish4 = tweet4.indexOf(";");
    String latitude = tweet4.substring(start4,  finish4);
    String latitude2 = tweet4.substring(4, finish4);


    String tweet5 = tweet4.substring(finish4 + 1);
    int start5 = tweet5.indexOf("#");
    int finish5 = tweet5.indexOf(";");
    String longitude = tweet5.substring(start5, finish5);
    String longitude2 = tweet5.substring(4, finish5);



    */
    System.out.println();
    System.out.println("Type: " + type_2);
    System.out.println("Detail: " + detail2);
    System.out.println("Location: " + location2);
    //System.out.println("Latitude: " + latitude2);
    //System.out.println("Longitude: " + longitude2);

    keyboard.close();

忽略这一行的注释部分,String location = tweet3.substring(start3, finish3);,给了我这个错误,40.022;线程“main”中的异常 java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:- 2 在 java.lang.String.substring(未知来源) 在 ParseTheTweet.main(ParseTheTweet.java:31)。

我注释掉了其他部分以在给定的输入上测试我的代码,并且它一直有效。关于为什么会这样的任何想法?

【问题讨论】:

  • 该异常准确地解释了问题所在 - 您将 -2 传递给 substring,我认为(您应该查找它,而不是我!)意味着较早的函数调用未能找到 @ 987654323@或;
  • 检查 start3 或 finish3 的任何值是否为有效值且不是负数。

标签: java string


【解决方案1】:

虽然您的代码需要经度信息,但您的输入没有经度信息并且是 StringIndexOutofBounds 的原因。

输入一些类似的东西,它应该可以工作。

典型报价; #det 免费基本用品 4 只疏散宠物。 #loc 2323 第 55 街,博尔德; #lat 40.022;#long 40.022;

【讨论】:

    【解决方案2】:

    根据您的输入 tweet4 = #lat 40.022;finish4 = 12。由于输入字符串tweet4.substring(finish4 + 1) 中没有经度信息,因此将空返回为tweet5

    此外,start5finish5 变为 -1。因此tweet5.substring(start5, finish5) 被评估为"".substring(-1, -1) 导致StringIndexOutOfBoundsException

    因此您必须在输入文本中添加经度信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-01
      • 2013-12-08
      • 1970-01-01
      • 1970-01-01
      • 2013-03-05
      • 2012-10-03
      • 2014-10-16
      • 2017-03-22
      相关资源
      最近更新 更多