2017-09-07 38 views
-1

這裏是輸入我應該解析:#typ offer; #免費基本用品4 evacs寵物。 #loc 2323 55th st,boulder; #lat 40.022;這是我的代碼: System.out.print(「以正確的格式輸入推文:」); String tweet = keyboard.nextLine();字符串索引超出Java的界限例外

int start = tweet.indexOf("#"); 
    int finish = tweet.indexOf(";"); 
    String type = tweet.substring(start, finish); 
    String type2 = type.substring(4,finish); 
    String type_2 = type2.toUpperCase(); 



    String tweet2 = tweet.substring(finish + 1); 
    int start2 = tweet2.indexOf("#"); 
    int finish2 = tweet2.indexOf(";"); 
    String detail = tweet2.substring(start2, finish2); 
    String detail2 = tweet2.substring(5, finish2); 



    String tweet3 = tweet2.substring(finish2 + 1); 
    int start3 = tweet3.indexOf("#"); 
    int finish3 = tweet3.indexOf(";"); 
    String location = tweet3.substring(start3 , finish3); 
    String location2 = tweet3.substring(4, finish3); 

    /* 
    String tweet4 = tweet3.substring(finish3 + 1); 
    int start4 = tweet4.indexOf("#"); 
    int finish4 = tweet4.indexOf(";"); 
    String latitude = tweet4.substring(start4, finish4); 
    String latitude2 = tweet4.substring(4, finish4); 


    String tweet5 = tweet4.substring(finish4 + 1); 
    int start5 = tweet5.indexOf("#"); 
    int finish5 = tweet5.indexOf(";"); 
    String longitude = tweet5.substring(start5, finish5); 
    String longitude2 = tweet5.substring(4, finish5); 



    */ 
    System.out.println(); 
    System.out.println("Type: " + type_2); 
    System.out.println("Detail: " + detail2); 
    System.out.println("Location: " + location2); 
    //System.out.println("Latitude: " + latitude2); 
    //System.out.println("Longitude: " + longitude2); 

    keyboard.close(); 

忽略的註釋部分這條線,字符串位置= tweet3.substring(START3,finish3);,是給我此錯誤,40.022;例外在線程 「主要」 java.lang.StringIndexOutOfBoundsException:字符串索引超出範圍:-2 位於ParseTheTweet.main(ParseTheTweet.java:31)的java.lang.String.substring(未知源) 。

我評論了其他部分,以測試我的代碼在給定的輸入,它的工作,直到那一點。有關爲什麼會出現這種情況的任何想法?

+0

這個異常解釋了什麼是錯誤的 - 你傳遞-2到'substring'中,我認爲(你應該查找它,而不是我!)意味着更早的函數調用未能找到'#'或'; '。 –

+0

檢查start3或finish3的值是否爲有效值且不是負值。 – Soumya

回答

0

雖然您的代碼需要經度信息,但您的輸入沒有經度信息,並且是StringIndexOutofBounds的原因。

輸入一些東西,它應該工作。

典型報價; #免費基本用品4 evacs寵物。 #loc 2323 55th st,boulder; #lat 40.022; #long 40.022;

0

根據你輸入的 tweet4 = #lat 40.022;finish4 = 12。由於輸入字符串tweet4.substring(finish4 + 1)中沒有經度信息,因此返回空值爲tweet5

此外start5finish5變成-1。因此tweet5.substring(start5, finish5)評估爲"".substring(-1, -1),這導致StringIndexOutOfBoundsException

因此,您必須在輸入文本中添加經度信息。