简体   繁体   English

“异常:java.lang.StringIndexOutOfBoundsException:字符串索引超出范围”

[英]“Exception:java.lang.StringIndexOutOfBoundsException: String index out of range”

Here is the problem: Return true if the string "cat" and "dog" appear the same number of times in the given string. 这是问题所在:如果字符串“ cat”和“ dog”在给定的字符串中出现相同的次数,则返回true。 Examples: catDog("catdog") → true; 例如:catDog(“ catdog”)→true; catDog("catcat") → false; catDog(“ catcat”)→false; catDog("1cat1cadodog") → true catDog(“ 1cat1cadodog”)→true

  public boolean catDog(String str) {
  int countCat=0;
  int countDog=0;
  for (int i=0; i<str.length();i++)
  {
     if (str.charAt(i)== 'c'&& str.length()>=3)
       {
          if (str.substring(i,i+3).equals("cat"))
          countCat++;
       }
  }
  for (int i=0; i<str.length();i++)
  {
     if (str.charAt(i)== 'd' && str.length()>=3)
       {
          if (str.substring(i,i+3).equals("dog"))
          countDog++;
       }
  }
  if (countCat == countDog)
      return true;
  else
     return false;
}
str.substring(i,i+3).equals("cat")

i可能是最后一个,而i+3会给出错误

In your for loops conditions you are checking if entire String has length greater or equal 3 instead of checking only part from i till end. for循环条件中,您正在检查整个String的长度是否大于或等于3而不是仅检查从i到结尾的部分。 Try maybe with 尝试一下

str.length() - i >= 3

instead of 代替

str.length() >= 3

Why don't you simply use StringUtils#countMatches ? 为什么不简单地使用StringUtils#countMatches

StringUtils.countMatches(myStr, "cat") == StringUtils.countMatches(myStr, "dog");

Don't get lost with the indexes. 不要迷失在索引上。 However, if you don't want to use this method, debugging your code is the best thing you can do. 但是,如果您不想使用此方法,则调试代码是您可以做的最好的事情。

Okay, this is what I might do: 好的,这就是我可能会做的:

The problem was with your check str.length() >= 3 . 问题出在您的检查str.length() >= 3 It should have been i + str.length() . 应该是i + str.length()

I also suggest some changes to your code to get rid of duplication. 我还建议对代码进行一些更改以消除重复。 Here I extracted the part that counts the number of appearances of a substring and moved it to its own method. 在这里,我提取了计算子字符串出现次数的部分,并将其移至其自己的方法。 The part that checks if count of cat equals count of dog now calls said method twice. 现在检查猫数是否等于狗数的部分两次调用了上述方法。

public static void main(String[] args) {
    System.out.println(catDog("catdog"));
    System.out.println(catDog("catcat"));
    System.out.println(catDog("1cat1cadodog"));
    System.out.println(catDog("catdogcatc"));//Would previously throw error.
}

public static boolean catDog(String str) {
    int countCat = countAppearances(str, "cat");
    int countDog = countAppearances(str, "dog");
    return countCat == countDog;
}

private static int countAppearances(String str, String key) {
    int count = 0;
    for (int i = 0; i < str.length(); i++) {
        if (str.charAt(i) == key.charAt(0) && i + key.length() <= str.length()) {
            if (str.substring(i, i + key.length()).equals(key)) {
                count++;
            }
        }
    }
    return count;
}

You need to update your first condition before spiting you string like: 您需要先更新第一个条件,然后才能像下面这样吐出字符串:

if (str.charAt(i)== 'c' && (str.length() - i) >= 3)
{
    if (str.substring(i,i+3).equals("cat"))
        countCat++;
}
    public boolean catDog(String str) {
     int catCount = 0, dogCount = 0;
//run a for loop to check cat count
//run loop till 2nd last character
     for (int i = 0; i < str.length() - 2; i++) {
//now check if the charaters at positions matches "cat"
//if matches then increment cat count
      if (str.charAt(i) == 'c' && str.charAt(i + 1) == 'a' && str.charAt(i + 2) == 't') {
       catCount++;
      } else if (str.charAt(i) == 'd' && str.charAt(i + 1) == 'o' && str.charAt(i + 2) == 'g') {
//else check if the charaters at positions matches "dog"
//if matches then increment dog count
       dogCount++;
      }
     }

//check cat count and dog count
     if (catCount == dogCount) {
      return true;
     } else {
      return false;
     }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Java错误java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:0 - Java Error java.lang.StringIndexOutOfBoundsException: String index out of range: 0 无法弄清楚这个 java Exception: &quot;main&quot; java.lang.StringIndexOutOfBoundsException: String index out of range: 1 - Can't figure out this java Exception: "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1 “ main” java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:17 - “main” java.lang.StringIndexOutOfBoundsException: String index out of range: 17 java.lang.StringIndexOutOfBoundsException:字符串索引超出范围: - java.lang.StringIndexOutOfBoundsException: String index out of range: java.lang.StringIndexOutOfBoundsException:yuicompressor中的字符串索引超出范围 - java.lang.StringIndexOutOfBoundsException: String index out of range in yuicompressor java.lang.StringIndexOutOfBoundsException:字符串索引超出范围 - java.lang.StringIndexOutOfBoundsException: String index out of range java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:45 - java.lang.StringIndexOutOfBoundsException: String index out of range: 45 java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:1 - java.lang.StringIndexOutOfBoundsException: String index out of range: 1 java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:4 - java.lang.StringIndexOutOfBoundsException: String index out of range: 4 Java.Lang.Stringindexoutofboundsexception索引超出范围(0) - Java.Lang.Stringindexoutofboundsexception index out of range (0)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM