From 07ad26f686a265752908890863bc3809c6082951 Mon Sep 17 00:00:00 2001 From: Dmitry Khotinskiy Date: Fri, 6 May 2022 23:21:52 -0700 Subject: [PATCH] Update Exercise_18_17.java The prompt has been altered and the code was corrected in order to include the last character of the string in the character array. --- .../Exercise_18_17/Exercise_18_17.java | 41 +++++++++++-------- 1 file changed, 25 insertions(+), 16 deletions(-) diff --git a/Exercise_18/Exercise_18_17/Exercise_18_17.java b/Exercise_18/Exercise_18_17/Exercise_18_17.java index 9de58f8d..9332ad53 100644 --- a/Exercise_18/Exercise_18_17/Exercise_18_17.java +++ b/Exercise_18/Exercise_18_17/Exercise_18_17.java @@ -10,42 +10,51 @@ * 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. * +* * +* Sample Run * +* Enter a string: Welcome to Java * +* Enter a character: e * +* e appears 2 times * *********************************************************************************/ import java.util.Scanner; public class Exercise_18_17 { - /** Main method */ + // Main method public static void main(String[] args) { // Create a Scanner Scanner input = new Scanner(System.in); - // Prompt the user to enter a list of characters - System.out.print("Enter a list of characters in one line: "); + // Prompt the user to enter a string + System.out.print("Enter a string: "); String str = input.nextLine(); - char[] chars = new char[str.length() - 1]; - for (int i = 0; i < chars.length; i++) + + // Convert string into array of characters + char[] chars = new char[str.length()]; + for (int i = 0; i < chars.length; i++) { chars[i] = str.charAt(i); - char ch = str.charAt(str.length() - 1); + } + + // Prompt the user to enter a character + System.out.print("Enter a character: "); + char ch = input.next().charAt(0); // Display the number of occurrences of the character - System.out.println("The character \"" + ch + "\" occurs " - + count(chars, ch) + " times in the list \"" + - str.substring(0, str.length() - 1) + "\"."); + System.out.print(ch + " appears " + count(chars, ch) + " times"); } - /** Method counts the occurrences of a - * specified character in an array */ + // Method counts the occurrences of a character in an array public static int count(char[] chars, char ch) { return count(chars, ch, chars.length - 1); } - /** Recursive helper method */ + // Recursive helper method public static int count(char[] chars, char ch, int high) { - if (high < 0) // Base case + if (high < 0) { // Base case return 0; - else if (chars[high] == ch) + } else if (chars[high] == ch) { return 1 + count(chars, ch, high - 1); // Recursive call - else + } else { return count(chars, ch, high - 1); // Recursive call + } } -} \ No newline at end of file +}