得到java.lang.ArrayIndexOutOfBoundsException,看了看,找不到相同的例子

Getting java.lang.ArrayIndexOutOfBoundsException, looked, cannot find an example thats the same

我正在为我的 AP 计算机科学 Class 编写 "tweet checker" 代码。该代码应该检查推文的长度是否在 140 个字符的限制内,如果是,则打印使用的主题标签、@ 和链接的数量。我正在使用 .split 方法将所有字符放入一个数组中,然后我使用 for 循环访问该数组以查找特定字符。

我一直遇到 java.lang.ArrayIndexOutOfBoundsException,我知道这意味着我正在尝试访问字符串中不存在的元素,例如 46 个字符的数组的元素 46,但我不知道是什么确切的问题在这里。上次被吐槽的不是"looking hard enough"但是我就这个问题搜索了2个多小时,我只是个高中生

感谢所有帮助。

import java.util.Scanner;
import java.lang.Math; 

class Main{
    public static void main(String[] args)
     {
      Scanner scan = new Scanner (System.in);
      System.out.println("Please enter a tweet:");
      String tweet = scan.nextLine();
      int length = tweet.length ();
      String[] tweetArray = tweet.split ("");
      int c = 0;
      int d = 0;
      int e = 0;
      int i = 0;
      if (length > 140)
        System.out.println("Excess Characters: " + (length - 140));
      else
      {
        System.out.println("Length Correct");
        for (i = 0; i < length; i++)
        {
          if (tweetArray[i].equals("#"))
          {
            if(!tweetArray[i+1].equals(" "))
            {
              c++;
            }
          }
        }
        System.out.println("Number of Hastags: " + c);
        for (i = 0; i < length; i++)
        {
          if (tweetArray[i].equals("@"))
          {
            if(!tweetArray[i+1].equals(" "))
            {
              d++;
            }
          }
        }
          System.out.println("Number of Attributions: " + d);
          for (i = 0; i < length; i++)
          {
            if((tweetArray[i].equals("h")) || (tweetArray[i].equals("H")))
            {
              if(tweetArray[i+1].equals("t") || tweetArray[i+1].equals("T"))
              {
                if(tweetArray[i+2].equals("t") || tweetArray[i+2].equals("T"))
                {
                  if(tweetArray[i+3].equals("p") || tweetArray[i+3].equals("P"))
                  {
                    if(tweetArray[i+4].equals(":"))
                    {
                      if(tweetArray[i+5].equals("/"))
                      {
                        if(tweetArray[i+6].equals("/"))
                        {
                          if(!tweetArray[i+7].equals(" "))
                          {
                            e++;
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        System.out.println("Number of Links: " + e);
      }




}
}

在您的 for 循环中,i 正确地从 0 迭代到最大长度。但是你有这样的代码:

 tweetArray[i+1]
 ...
 tweetArray[i+7]

一旦 i 达到(或接近)其最大值,它将失败。也就是说,您引用的是数组末尾之后的内容。

一般来说,如果你需要检查下一个字符,你需要先检查它是否存在(因为你只知道当前字符存在)。

尽管如此,您可能希望回顾一下您的整个方法。似乎不需要将字符串拆分为字符。您可以改为使用基于字符串的函数来计算 @ 个字符的数量或检查是否存在字符串(例如 http://)。查看 the API