0

The Program I am trying to write will count the amount of "A"'s within a given string using recursion. What it should do is count how many times the program recurses itself. The Program compiles correctly but when run I am given this error

class hw10

{

public static void main(String[] args)
{
    System.out.println(f(""))
    System.out.println(f("A"));
    System.out.println(f("B"));
    System.out.println(f("BCA"));
    System.out.println(f("ABC"));
    System.out.println(f("ABACAD"));

}

public static int f(String s)
{

    if(s.length() <= 0)
    {
        if(s.charAt(0) == 'A')
        {
            return 1;
        }
        else
        {
            return 0;
        }


    }
    else
    {
        if(s.charAt(0) == 'A')
        {
            return 1 + f(s.substring(1));
        }
        else
        {
            return f(s.substring(1));
        }
    }

}

}

This is the full message Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0 at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:47) at java.base/java.lang.String.charAt(String.java:702) at hw10.f(hw10.java:20) at hw10.f(hw10.java:35) at hw10.main(hw10.java:7)

J Smith
  • 1
  • 2
  • 2
    Think about these lines carefully `if(s.length() <= 0) { if(s.charAt(0)`. – Carcigenicate Dec 05 '19 at 16:31
  • 1
    and this call System.out.println(f("")) – nano_nano Dec 05 '19 at 16:31
  • Does this answer your question? [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – MarsAtomic Dec 05 '19 at 16:50

1 Answers1

0

recursivity lead to short code try this :

        public static int f(String s) {
          if(s.length() == 0) return 0;
          if(s.charAt(0) == 'A') return (1 + f(s.substring(1)));
          return f(s.substring(1));
    }
kevin ternet
  • 4,514
  • 2
  • 19
  • 27