【发布时间】:2015-02-21 07:16:08
【问题描述】:
这是我收到的完整错误消息:
exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 27
at java.lang.String.charAt(String.java:646)
at Main.main(Main.java:268)
at Ideone.assertRegex(Main.java:110)
at Ideone.test(Main.java:42)
at Ideone.main(Main.java:28)
我在 DrJava 中为类分配编写了我的程序并且它可以工作,但是当我将我的代码输入到他们的代码运行器中时,我得到了运行时错误。我的代码如下:
import java.io.*;
import static java.lang.System.*;
import java.util.Scanner;
class Main{
public static void main (String str[]) throws IOException {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a tweet:");
String tweet = scan.nextLine();
int length = tweet.length();
if(length > 140){
System.out.println("Excess Characters: " + (length - 140));}
else{
System.out.println("Length Correct");
int countera = 0;
for( int i=0; i<tweet.length(); i++ ) {
if( tweet.charAt(i) == '#' ) {
i++;
if (( tweet.charAt(i) != ' ' ) && ( tweet.charAt(i) != '\t' ))
countera++;
}
}
int counterb = 0;
for( int i=0; i<tweet.length(); i++ ) {
if( tweet.charAt(i) == '@' ) {
i++;
if (( tweet.charAt(i) != ' ' ) && ( tweet.charAt(i) != '\t' ))
counterb++;
}
}
int counterc = 0 ;
String search = "http://";
for ( int i = -1 ; ( i = tweet.indexOf( search, i + 1 ) ) != -1 ; counterc ++ );
System.out.println("Number of Hashtags: " + countera);
System.out.println("Number of Attributions: " + counterb);
System.out.println("Number of Links: " + counterc);
}
}
}
【问题讨论】:
-
您可能希望使用
Character.isWhitespace(c)来测试白人步伐作为“单词”之间的分隔符,而不是' '和'\t'。
标签: java string runtime-error