|
| 1 | +package ch_18; |
| 2 | + |
| 3 | +import java.util.Scanner; |
| 4 | + |
| 5 | +/** |
| 6 | + * *18.17 (Occurrences of a specified character in an array) Write a recursive method that |
| 7 | + * finds the number of occurrences of a specified character in an array. You need to |
| 8 | + * define the following two methods. The second one is a recursive helper method. |
| 9 | + * public static int count(char[] chars, char ch) |
| 10 | + * public static int count(char[] chars, char ch, int high) |
| 11 | + * Write a test program that prompts the user to enter a list of characters in one line, |
| 12 | + * and a character, and displays the number of occurrences of the character in the list. |
| 13 | + */ |
| 14 | +public class Exercise18_17 { |
| 15 | + public static void main(String[] args) { |
| 16 | + Scanner in = new Scanner(System.in); |
| 17 | + System.out.print("Enter a list of characters in one line: "); |
| 18 | + String line = in.nextLine(); |
| 19 | + char[] chars = line.toCharArray(); |
| 20 | + |
| 21 | + System.out.println("Enter a single character: "); |
| 22 | + char ch = in.next().charAt(0); |
| 23 | + System.out.println("The character " + ch + " occurs " + count(chars, ch) + " times."); |
| 24 | + in.close(); |
| 25 | + } |
| 26 | + |
| 27 | + public static int count(char[] chars, char ch) { |
| 28 | + return count(chars, ch, chars.length - 1); |
| 29 | + } |
| 30 | + |
| 31 | + public static int count(char[] chars, char ch, int high) { |
| 32 | + if (high > 0) { |
| 33 | + return chars[high] == ch ? (1 + count(chars, ch, high - 1)) : (count(chars, ch, high - 1)); |
| 34 | + } else { |
| 35 | + return 0; |
| 36 | + } |
| 37 | + } |
| 38 | +} |
0 commit comments