![](/img/trans.png)
[英]Why do I keep geting: Exception in thread “main” java.lang.StringIndexOutOfBoundsException: String index out of range: 4
[英]I keep getting this error : Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 28
這是我的代碼:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String tweet = scan.nextLine();
int link = 0;
int tag = 0;
int at = 0;
int c = 0;
int l = tweet.length();
if (l <= 140) {
while (c < tweet.length()) {
char let = tweet.charAt(c);
if (let == '#') {
tag++;
String hash = tweet.substring(c, c + 2);
if (hash.equals("# ")) {
tag--;
}
} else if (let == '@') {
at++;
String to = tweet.substring(c, c + 2);
if (to.equals("@ ")) {
at--;
}
} else if (let == 'h') {
String http = tweet.substring(c, c + 7);
if (http.equals("http://")) {
link++;
}
}
c++;
}
System.out.println("Number of Hashtags: " + tag);
System.out.println("Number of Attributions: " + at);
System.out.println("Number of Links: " + link);
} else if (l > 140) {
int difference = tweet.length() - 140;
System.out.print("Excess Characters: " + difference);
}
}
}
每次我運行它我都會收到錯誤:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 28
at java.lang.String.substring(String.java:1951)
at Main.main(Main.java:268)
at Ideone.assertRegex(Main.java:110)
我只是想知道是否有辦法解決它?
在 do subString 之前添加范圍檢查,因為 tweet.substring(c, c + 2); 當推文長度為7,c當前為6,c+2為8,超過長度時,可能會導致索引越界錯誤。
if (let == '#') {
tag++;
if (c < tweet.length() - 2) { // make sure c+2 is in range for the substring function
String hash = tweet.substring(c, c + 2);
if (hash.equals("# ")) {
tag--;
}
}
} else if (let == '@') {
at++;
if (c < tweet.length() - 2) {// make sure c+2 is in range for the substring function
String to = tweet.substring(c, c + 2);
if (to.equals("@ ")) {
at--;
}
}
} else if (let == 'h') {
if (c < tweet.length() - 7) {// make sure c+7 is in range for the substring function
String http = tweet.substring(c, c + 7);
if (http.equals("http://")) {
link++;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.