为什么我得到运行时错误:StringIndexOutOfBounds?

时间:2016-03-30 03:02:38

标签: java runtime-error

立即完成我的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);

   }

}
}

1 个答案:

答案 0 :(得分:1)

由于(ch++)<=(tweet.length()),在检查此条件if(tweet.charAt(ch) == '#' && ((ch++)<=(tweet.length())) && (tweet.charAt(ch++)!=' ' && tweet.charAt(ch++)!='\t')) { hash++; } 后,ch的值会增加。

说明:

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);

   }

}
}

对于上面的代码,有4个条件(对于i = 0):

  1. tweet.charAt(ch)ch = 0
  2. ((ch ++)&lt; =(tweet.length()))ch = 0,但是ch ++,所以在条件检查后,该值将增加。
  3. (tweet.charAt(ch ++)ch = 1(由于第2点)
  4. tweet.charAt(ch ++)ch = 2(出于同样的原因)。
  5. 试试这个:

    drawImageAt
相关问题