gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 12:32:23 24 4
gpt4 key购买 nike

我收到此错误消息:

线程“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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com