【问题标题】:Exception in thread "main java.lang.StringIndexOutOfBoundsException: String index out of range线程“main java.lang.StringIndexOutOfBoundsException:字符串索引超出范围”中的异常
【发布时间】: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 语句(或简单地使用您的调试器)来查看在那之前发生了什么。追溯你的错误。 (这称为“调试”。)

标签: java eclipse


【解决方案1】:

我能够调用一个类似的错误条件,其中我选择了一个正的开始子字符串,但我的结束子字符串为 -1。

在这种情况下,它可能是由您的 finish 变量包含值 -1 引起的,这意味着找不到分号。

...那个的原因是因为您使用的是Scanner#next(),它只会消耗up until the next whitespace value

扫描器使用分隔符模式将其输入分解为标记,默认情况下匹配空格。然后可以使用各种 next 方法将生成的标记转换为不同类型的值。

来自Scanner.next()

从此扫描器中查找并返回下一个完整的令牌。一个完整的标记前后是匹配分隔符模式的输入。

在这种情况下,分隔符模式全是空格,因为您没有更改默认行为。

为了让事情变得更简单,请将其更改为使用 nextLine()

【讨论】:

  • ... 并在调用 next() 之前使用 hasNext()。 (同样适用于 hasNextLine)。
  • @NoDataFound:如果这是从文件读取,我可以看到使用它,但由于它是从 STDIN 读取的,因此程序的执行实际上会阻塞,直到它读取一个换行符。因此,在这种情况下,我不会看到 hasNextLine 背后的太多目的。
  • 我这么说是为了完成,因为他可以(如果需要)将try {} catch(NoSuchElementException) 转换为布尔测试并做一些事情(比如询问有效数字等)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-20
  • 1970-01-01
  • 2019-03-11
  • 2014-01-27
  • 2015-06-30
  • 2012-07-27
  • 2012-11-27
相关资源
最近更新 更多