![](/img/trans.png)
[英]Error after compiling Java project : Exception in thread “main” java.lang.StringIndexOutOfBoundsException: String index out of range: 0
[英]Exception in thread "main java.lang.StringIndexOutOfBoundsException: String index out of range
我收到此錯誤消息:
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行注釋。 輸入的推文為:
#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);
我的代碼有什么問題?
我能夠調用類似的錯誤條件,在該條件下,我選擇了一個正的開始子字符串,但將-1作為我的結束子字符串。
在這種情況下,這可能是由於您的finish
變量包含值-1所致,這意味着找不到分號。
...之所以這樣,是因為您使用的是Scanner#next()
,它只會消耗直到下一個空格值 。
掃描程序使用定界符模式將其輸入分為令牌, 默認情況下 ,該模式與whitespace匹配 。 然后,可以使用各種下一種方法將生成的令牌轉換為不同類型的值。
從Scanner.next()
:
查找並返回此掃描儀的下一個完整令牌。 完整的標記在其前面,然后是與定界符模式匹配的輸入。
在這種情況下,分隔符模式為所有空格,因為您沒有更改默認行為。
為了使事情更簡單, nextLine()
更改為使用nextLine()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.