简体   繁体   English

字符串索引超出范围错误

[英]String Index Out of Bounds Error

The following code is attempting to Given a string, compute recursively (no loops) the number of lowercase 'x' chars in the string. 以下代码试图给定一个字符串,以递归方式(无循环)计算字符串中小写字母'x'的字符数。

The code is having this error: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0 代码出现此错误:线程“主”中的异常java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:0

The main method for this code is: 此代码的主要方法是:

public static void main(String [] args)
{
  System.out.println(countX("hx1x"));
}

The actual code is: 实际的代码是:

public static int countX(String str)
{ 
    if(str.charAt(0) != 'x')
    {
        if(str.indexOf('x') >= 1)
        {
            return countX(str.substring(1, str.length()));
        }
        else
        {
            return 0;
        }
    }
    else
    {
        return 1 + countX(str.substring(1, str.length()));
    }
}

Just add 只需添加

    if (str.length() <= 0) return 0;

at start of countX(...) 在countX(...)开始时

The exception is thrown at 抛出异常

    if(str.charAt(0) != 'x')

when str is "" 当str为“”时

Btw. 顺便说一句。 the code is not exactly effective, when creating new strings for each char check. 在为每个字符检查创建新字符串时,该代码并不完全有效。 Also recursive functions like this throw StackOverflowError with long enough input. 像这样的递归函数也将使用足够长的输入抛出StackOverflowError。

Look at this: Java: How do I count the number of occurrences of a char in a String? 看一下这一点: Java:如何计算字符串中char出现的次数?

You're missing the base case of the recursion - what happens if the string has zero length? 您缺少递归的基本情况-如果字符串的长度为零会发生什么? Try this: 尝试这个:

public static int countX(String str) {
    if (str.length() == 0)
        return 0;
    else if (str.charAt(0) == 'x')
        return 1 + countX(str.substring(1));
    else
        return countX(str.substring(1));
}

Alternatively, you could omit the substring operation and pass around the index you're currently in - it's more efficient this way, as it avoids the creation of unnecessary string objects 另外,您可以省略子字符串操作并传递当前所在的索引-这样更有效,因为它避免了创建不必要的字符串对象

public static int countX(String str, int idx) {
    if (idx == str.length())
        return 0;
    else if (str.charAt(idx) == 'x')
        return 1 + countX(str, idx+1);
    else
        return countX(str, idx+1);
}

Then, you'd call the method like this: 然后,您将调用如下方法:

countX("hx1x", 0)

Write a set of unit tests for your function. 为您的功能编写一组单元测试。 For now, this could be as simple as some lines like 现在,这可能像一些行一样简单

assertEquals(2, countX("hx1x", 0));

to your main(). 到您的main()。 Start with really simple cases, like: 从非常简单的案例开始,例如:

assertEquals(0, countX("", 0));
assertEquals(0, countX("a", 0));
assertEquals(1, countX("x", 0));

These will be even easier to debug - use a debugger if you must, but if your example is simple like these, it will probably not even be necessary. 这些将更易于调试-如果必须,请使用调试器,但是如果您的示例像这样简单,则可能甚至没有必要。

Why make it so complicated when you can do something simple? 当您可以做一些简单的事情时,为什么要使其变得如此复杂呢? Here is a much simpler solution to your problem: 这是解决您的问题的简单得多的方法:

    int count=0;
    for(int i = 0; i< str.length(); i++){
        if(str.charAt(i) == 'x') count++;
    }

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM