i cant find the right solution for this exercise, here is the task:
(Occurrences of a specified character in an array) Write a recursive method that finds the number of occurrences of a specified character in an array. You need to define the following two methods. The second one is a recursive helper method.
public static int count(char[] chars, char ch)
public static int count(char[] chars, char ch, int high)
Write a test program that prompts the user to enter a list of characters in one line, and a character, and displays the number of occurrences of the character in the list.
1) I can solve it only if I add another parameter (int index) but how can I do it without adding another parameter or using for loop ?
2)Why is the helper method there? I don't understand the purpose of helper methods in recursion.
Here is my solution:
package occurencesinarray;
import java.util.Scanner;
public class Start {
public static void main(String[] args){
System.out.println("Enter few characters: ");
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
char[] chars = new char[s.length()];
for(int i = 0; i < s.length(); i++){
chars[i] = s.charAt(i);
}
System.out.println("Enter desired character: ");
char ch = scan.nextLine().charAt(0);
System.out.println(count(chars, ch));
}
public static int count(char[] chars, char ch){
return count(chars, ch, 0, 0);
}
public static int count(char[] chars, char ch, int high, int index){
if(index == chars.length){
return high;
}
if(chars[index] == ch){
return count(chars, ch, high + 1, index + 1);
} else{
return count(chars, ch, high, index + 1);
}
}
}