Reputation: 109
I am trying to calculate the number of characters in a string by using recursive method. here is my code in java
public class MainClass {
public int length(String str) {
if (str == null) {
return 0;
} else {
return length(str.substring(1))+1; // in eclipse it says : at MainClass.length(MainClass.java:12)
}
}
public static void main(String args[]) {
MainClass m = new MainClass();
System.out.println(m.length("ali"));
}
}
This line does not work : return length(str.substring(1))+1;
How can I correct the code?
Thanks
Upvotes: 1
Views: 107
Reputation: 9633
It should be
public int length(String str) {
if (str==null||str.isEmpty()) {
return 0;
}else {
return length(str.substring(1))+1
}
Upvotes: 1
Reputation: 11934
You forgot the case when your String
argument is an empty string, include that in your check:
if (str == null || str.length()==0) {
return 0;
} else {
[...]
Please note that the Exception that you get contains valuable information about what's going wrong, in this case it's probably a StringIndexOutOfBoundsException
because you call substring(1)
on an empty String
object.
Upvotes: 3