【发布时间】:2014-09-14 23:54:51
【问题描述】:
我收到此错误消息:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -6 at java.lang.String.substring(Unknown Source) at ParseTheTweet.main(ParseTheTweet.java:41)
尝试运行我的程序时。在贴出的代码之前有 24 行 cmets。输入的推文是:
#typ structure; #det damaged; #loc 224 left fork road (shed) (house okay); #lat 40.029854; #lng -105.391055;
public class Tweet {
public static void main(String[] args) {
Scanner theScanner = new Scanner(System.in);
String tweet, typ, det, loc, lat, lng;
System.out.println("Enter tweet here:");
tweet = theScanner.next();
int start, finish;
typ = tweet;
start = typ.indexOf("#")+ 5;
finish = typ.indexOf(";");
typ = typ.substring(start, finish);
typ = typ.trim();
tweet = tweet.substring(finish+1);
System.out.println("Type:" + "\t" + "\t" + typ);
我的代码有什么问题?
【问题讨论】:
-
当你的字符串中既没有出现井号也没有出现分号时会发生什么?
-
你应该检查'#'和';'发生在
typ,否则无法正常获取子字符串,抛出刚才看到的异常。 -
你为什么要在
typ.indexOf("#")上加5? -
怎么了??您试图对字符串的字符 -6 进行寻址。异常信息会告诉您这发生在哪一行,因此很容易添加 println 语句(或简单地使用您的调试器)来查看在那之前发生了什么。追溯你的错误。 (这称为“调试”。)