Reputation: 1
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)
Upvotes: 0
Views: 398
Reputation: 4612
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));
}
Upvotes: 0