[英]I keep getting this error : Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 28
This is my code :这是我的代码:
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);
}
}
}
Every time i run it I get the error:每次我运行它我都会收到错误:
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)
I was just wondering if there is a way to fix it?我只是想知道是否有办法解决它?
Add a range check before your do subString because tweet.substring(c, c + 2);在 do subString 之前添加范围检查,因为 tweet.substring(c, c + 2); might cause index out of bound error when, for example, the tweet length is 7, c is currently 6, c+2 is 8, which exceeds the length.
当推文长度为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.