字符串索引越界错误

发布于 2024-12-11 18:45:37 字数 650 浏览 0 评论 0原文

以下代码尝试给定一个字符串,递归(无循环)计算字符串中小写“x”字符的数量。

代码有这个错误: 线程“main”中的异常 java.lang.StringIndexOutOfBoundsException: String index out of range: 0

此代码的主要方法是:

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

实际代码是:

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

The following code is attempting to Given a string, compute recursively (no loops) the number of lowercase 'x' chars in the string.

The code is having this error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 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()));
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

如梦初醒的夏天 2024-12-18 18:45:37

添加即可

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

只需在 countX(...) 的开头

顺便说一句时,会引发异常

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

,当 str 为 ""

。在为每个字符检查创建新字符串时,该代码并不完全有效。像这样的递归函数也会在输入足够长的情况下抛出 StackOverflowError 。

看看这个:
Java:如何做我计算字符串中某个字符出现的次数?

Just add

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

at start of countX(...)

The exception is thrown at

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

when str is ""

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.

Look at this:
Java: How do I count the number of occurrences of a char in a String?

命比纸薄 2024-12-18 18:45:37

您缺少递归的基本情况 - 如果字符串长度为零会发生什么?试试这个:

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

或者,您可以省略子字符串操作并传递您当前所在的索引 - 这种方式更有效,因为它避免创建不必要的字符串对象

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

然后,您可以像这样调用该方法:

countX("hx1x", 0)

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)
耶耶耶 2024-12-18 18:45:37

为您的函数编写一组单元测试。现在,这可能就像

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

main() 中的一些行一样简单。从非常简单的情况开始,例如:

assertEquals(0, countX("", 0));
assertEquals(0, countX("a", 0));
assertEquals(1, countX("x", 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(). 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.

℉絮湮 2024-12-18 18:45:37

当你可以做一些简单的事情时,为什么要把事情搞得这么复杂呢?这是解决您问题的更简单的方法:

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

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++;
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文