Java Write a static recursive method named frequencyCount(n,d) that returns the
ID: 3805160 • Letter: J
Question
Java
Write a static recursive method named frequencyCount(n,d) that returns the frequency of occurrence of a particular digit d in an integer n. For example, frequencyCount(1342457,4) returns 2,
but frequencyCount(1342457,6) returns 0.
The method frequencyCount(n,d) may not use local variables or static variables.
Create a project named Project7 containing a class named Program7 which contains the main method for this application as well as the method frequencyCount. The main method for this application reads in an integer n as well as a digit d and then calls the method frequencyCount to output the result on the screen.
Explanation / Answer
FrequencyCountTest.java
public class FrequencyCountTest {
public static void main(String[] args) {
System.out.println(frequencyCount(1342457,6));
System.out.println(frequencyCount(1342457,4) );
}
public static int frequencyCount(int n, int searchDigit){
if(n == 0){
return 0;
}
else{
if(n % 10 == searchDigit){
return 1 + frequencyCount(n/10, searchDigit);
}
else{
return frequencyCount(n/10, searchDigit);
}
}
}
}
Output:
0
2
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.