java - 线程中的异常“main java.lang.StringIndexOutOfBoundsException : String index out of range

标签 java eclipse

我收到此错误消息:

线程“main”中的异常 java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:-6 位于 ParseTheTweet.main(ParseTheTweet.java:41) 处的 java.lang.String.substring(未知来源)

当尝试运行我的程序时。贴出的代码前有24行注释。输入的推文是:

#typ结构; #det损坏; #loc 224 左岔路(棚子)(房子还可以); #纬度 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);

我的代码有什么问题吗?

最佳答案

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

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

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

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.

来自Scanner.next():

Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.

在本例中,分隔符模式全是空格,因为您没有更改默认行为。

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

关于java - 线程中的异常“main java.lang.StringIndexOutOfBoundsException : String index out of range,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25839160/

相关文章:

java - ElasticSearch SearchResponse 对象聚合到 JsonObject?

java - 为具有(模拟的)可选/默认参数的函数编写 Javadoc

java - 评论数量的增加是否会增加执行时间?

java - 在 Eclipse 中分析 Java OO 代码

java - 如何从文件中读取多个相同的对象

java - 使用 xml 属性在 java 中进行 XML 到 JSON 的转换

java - Android 解析无法将子类列表固定到缓存

java - 在 Eclipse HELIOS\jre\bin\javaw.exe 中找不到 Java 虚拟机错误

java - 导入org.springframework无法解决

java - If 和 else 同时声明虽然这不应该是可能的