简体   繁体   中英

using recursion error. Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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