countChar(s,ch) returns the number of times the character ch occurs in the strin
ID: 3728685 • Letter: C
Question
countChar(s,ch) returns the number of times the character ch occurs in the string s. For example, if s="committee" and ch='m' then countChar(s,ch) will return 2. You are to do this recursively.
import java.util.Scanner;
public class Lab12Num3 {
public static int countChar(String str, char character) {
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//input the string
String x = sc.nextLine();
//input the character as a string
String y = sc.nextLine();
//get the character
char ch = y.charAt(0);
System.out.println(countChar(x,ch ));
}
}
Explanation / Answer
import java.util.Scanner;
public class Lab12Num3 {
public static int countChar(String str, char character) {
int count = 0;
for(int i=0; i<str.length(); i++)
if(str.charAt(i) == character)
count++;
return count;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//input the string
String x = sc.nextLine();
//input the character as a string
String y = sc.nextLine();
//get the character
char ch = y.charAt(0);
System.out.println(countChar(x,ch ));
}
}
/*
Sample run:
this is my first line
c
0
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.