Ask your own question, for FREE!
Computer Science 4 Online
OpenStudy (anonymous):

Tricky Java Recursion question: Write a program that prompts for and reads in a string. Your program should call a recursive method stringLength, passing it the string. stringLength should return the length of the string. Implement stringLength using recursion. Do not use the length method in the string object. Test your program with the string " " (the null string), "A", and "ABCDEF".

OpenStudy (anonymous):

So far, this is what I have but according to the instructions, it says that I can't use the length method in the string object so this doesn't count? import java.util.Scanner; class C14h3 { public static void main(String[] args) { String line; int count2; Scanner kb = new Scanner(System.in); line = kb.nextLine(); count2 = stringLength(line); System.out.println(count2); } public static int stringLength(String s) { int count = 0; //creating counter that counts string length while (count < s.length()) { stringLength(s.substring(0,count++)); } return count; //returning counter that has string length. } }

OpenStudy (lyrae):

Why would you need to count the chars in the string if you can use the .length() method? You could just return s.lenght() and you would be done! But that's not the case! The point of this assignement is to learn how to make your own count method and it would be weird if thed'd allow you to use an existing one. A recursive function always have a base case to stop the recursion and a recursive case to do another recursion. Here's an example on how to calcluate factorials recursively: ``` public int factorial(int a) { if (a == 1) return 1; // Base case stops recursion else return a * factorial(a-1); // Recursive case } ``` In your stringLength method you need to fix a few things ``` public static int stringLength(String s) { if (condition for base case) { return 0; } else { return 1 + stringLength(s.substring(an argument which return s minus one character)); } } ```

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!