【发布时间】: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 的任何值是否为有效值且不是负数。