Java 字符串索引超出范围:7错误

Java 字符串索引超出范围:7错误,java,Java,您好,我正在编写一个代码,要求用户发送一条tweet,然后告诉用户tweet的长度是否正确,以及其中有多少个“s@”和链接,但每次运行时,我都会得到错误字符串索引或范围:7。有什么想法吗 import java.util.Scanner; import java.lang.Math; class Main { public static void main(String[] args) { Scanner scan = new Scanner (System.

您好,我正在编写一个代码,要求用户发送一条tweet,然后告诉用户tweet的长度是否正确,以及其中有多少个“s@”和链接,但每次运行时,我都会得到错误字符串索引或范围:7。有什么想法吗

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 hashtags = 0;
        int attributions = 0;
        int links = 0;


        if (tweet.length() > 140) {
          int excess = tweet.length()-140;
          System.out.println ("Excess Characters: " + excess);
        } else {
          System.out.println ("Length Correct.");
          while (tweet.length() <= 140) {
            if (tweet.charAt(0) == '#'){
              hashtags ++;
            }
            if (tweet.charAt(0) == '@'){
              attributions ++;
            }
            if (tweet.substring(0,8) == "http://") {
              links ++;
            }
            tweet = tweet.substring(1);
            }
          System.out.println ("Number of Hashtags: " + hashtags);
          System.out.println ("Number of Attributions: " + attributions);
          System.out.println ("Number of Links: " + links);
        }
    }
}

至少有两个问题。首先,您不应该在太短的字符串上使用子字符串。最好使用:

这样,您甚至不必担心字符串的长度,也不必担心字符计数错误,或者因为使用==而不是:-

第二,关于以下准则:

while (tweet.length() <= 140) {
    :
    tweet = tweet.substring(1);
}

第一个问题是,您试图获取tweet字符串的8长度子字符串,而不知道tweet的长度。如果tweet只有6个字符怎么办?如果是,则会得到一个索引越界异常,因为在数组结束处查看两个索引

您应该添加一个条件保护:

if (tweet.length() >= 8 && tweet.substring(0,8).equals("http://")) {
    links++;
}
&&运算符意味着如果字符串长度小于8,将永远不会检查tweet.substring,因此可以避免跳出边界

第二个问题是,即使你加入了条件卫士,你所做的也毫无意义。substringbeginIndex、endIndex返回的字符串长度等于endIndex-beginIndex,本例中为8。字符串http://只有七个字母,因此从逻辑上讲,8个字符的字符串不可能与之相等。使用startsWith函数,而不是0位置的子字符串:

前面的行应该是这样的:

if (tweet.startsWith("http://")) {
    links++;
}

您绝对应该使用for循环:

String string= "hello";
for (int i = 0; i < string.length(); ++i)
{
    if (string.charAt( i ) == '#')
    {
        //do something
    }
}
这将确保正确遍历整个字符串


其次,在假设之前,需要确保子字符串0、8在边界内。这可能是导致您在某些测试用例中出错的原因。

那么,您是否已经在调试器中逐步完成了代码,检查了变量等?看看您的解析逻辑http://One 旁注,在Java中,您使用string.equals检查字符串的相等性。这是怎么回事?我给出了一个更简单的方法遍历tweet/字符串的建设性示例,并指出了最有可能导致越界错误的原因。
if (tweet.startsWith("http://")) {
    links++;
}
String string= "hello";
for (int i = 0; i < string.length(); ++i)
{
    if (string.charAt( i ) == '#')
    {
        //do something
    }
}