Java Project Programming Help Please! Write a program that prompts for and reads
ID: 3807969 • Letter: J
Question
Java Project Programming Help Please!
Write a program that prompts for and reads in a string, then prints a message saying how many lower case ‘x’ is in this string.
Your program should contain two methods: a main method reads in the string and a recursive (static) method countX that takes the string as input and returns the number of lowercase character ‘x’ in this string. Make sure your method solves the problem using a recursive way, not a loop structure.
The following methods might be helpful, but you are not required to use all of them:
For a string s in Java,
s.length() returns the number of charaters in s
s.charAt(i) returns the ith character of s, 0-based
s.substring(i,j) returns the substring that starts with the ith character of s and ends with the j-1st character of s (not the jth), both 0-based.
So if s=“happy”, s.length=5, s.charAt(1)=a, and s.substring(2,4) = “pp”.
Explanation / Answer
import java.util.Scanner;
public class CountCharacters
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a String: ");
String s = sc.nextLine().toLowerCase(); //Reading string from the user
int cn = countX(s, 'x',0, 0); // Calling function
System.out.println("character 'x'" + " occurs " + cn + " times in String: " + s);
sc.close();
}
private static int countX(String str, char c,int index,int count)
{
if ( str.length()>index)
{
if (c == str.charAt(index))
{
count++;
}
index++;
count = countX(str, c, index, count); //Recursive function
}
return count;
}
}
Output:
Enter a String: x ix zzz xxx x
character 'x' occurs 6 times in String: x ix zzz xxx x
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.