现在正在做我的 AP 计算机科学作业,但我遇到了运行时错误。有谁知道我的代码有什么问题吗? 该程序在 Dr.Java 上运行良好,但在我的网站测试器上显示运行时错误...
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 hash = 0;
int attr = 0;
int link = 0;
int ch = 0;
if(tweet.length()>140)
{
System.out.println("Excess Characters: " + (tweet.length() - 140 ));
}
else
{
tweet=tweet.toLowerCase();
System.out.println("Length Correct");
for(ch=0; ch<tweet.length(); ch++)
{
if(tweet.charAt(ch) == '#' && ((ch++)<=(tweet.length())) && (tweet.charAt(ch++)!=' ' && tweet.charAt(ch++)!='\t'))
{
hash++;
}
if(tweet.charAt(ch) == '@' && ((ch++)<=(tweet.length())) && (tweet.charAt(ch++)!=' ' && tweet.charAt(ch++)!='\t'))
{
attr++;
}
if(tweet.charAt(ch) == 'h' && ((ch + 7)<=(tweet.length())))
{
String a = new String("http://");
String sub = new String(tweet.substring(ch, ch + 7));
if (sub.equals(a))
{link++;}
}
}
System.out.println("Number of Hashtags: " + hash);
System.out.println("Number of Attributions: " + attr);
System.out.println("Number of Links: " + link);
}
}
}
最佳答案
因为ch++
检查此条件后 ch 的值会增加 (ch++)<=(tweet.length())
.
说明:
if(tweet.charAt(ch) == '#' && ((ch++)<=(tweet.length())) && (tweet.charAt(ch++)!=' ' && tweet.charAt(ch++)!='\t'))
{
hash++;
}
对于上面的代码,有 4 个条件(i=0):
- tweet.charAt(ch) ch = 0
- ((ch++)<=(tweet.length())) ch = 0,但 ch++ 因此在条件检查后该值将增加。
- (tweet.charAt(ch++) ch=1(因为第 2 点)
- tweet.charAt(ch++) ch = 2(出于同样的原因)。
试试这个:
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 hash = 0;
int attr = 0;
int link = 0;
int ch = 0;
if(tweet.length()>140)
{
System.out.println("Excess Characters: " + (tweet.length() - 140 ));
}
else
{
tweet=tweet.toLowerCase();
System.out.println("Length Correct");
for(ch=0; ch<tweet.length(); ch++)
{
if(tweet.charAt(ch) == '#' && ((ch+1)<(tweet.length())) && (tweet.charAt(ch+1)!=' ' && tweet.charAt(ch+1)!='\t'))
{
hash++;
}
if(tweet.charAt(ch) == '@' && ((ch+1)<(tweet.length())) && (tweet.charAt(ch+1)!=' ' && tweet.charAt(ch+1)!='\t'))
{
attr++;
}
if(tweet.charAt(ch) == 'h' && ((ch + 7)<(tweet.length())))
{
String a = new String("http://");
String sub = new String(tweet.substring(ch, ch + 7));
if (sub.equals(a))
{link++;}
}
}
System.out.println("Number of Hashtags: " + hash);
System.out.println("Number of Attributions: " + attr);
System.out.println("Number of Links: " + link);
}
}
}
关于java - 为什么我会收到运行时错误 :StringIndexOutOfBounds?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36298870/