user1008780
user1008780

Reputation: 21

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.

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

Upvotes: 2

Views: 2760

Answers (4)

Phil
Phil

Reputation: 3520

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

Upvotes: 0

Arnout Engelen
Arnout Engelen

Reputation: 6897

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.

Upvotes: 0

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236004

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)

Upvotes: 0

MarianP
MarianP

Reputation: 2759

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?

Upvotes: 1

Related Questions