[英]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.我正在尝试编写的程序将使用递归计算给定字符串中“A”的数量。 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)这是线程“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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.