6.31 LAB: Count characters - methods ----- javascript please
Write a program whose input is a character and a string, and whose output indicates the number of times the character appears in the string.
Ex: If the input is:
n Monday
the output is:
1
Ex: If the input is:
z Today is Monday
the output is:
0
Ex: If the input is:
n It's a sunny day
the output is:
2
Case matters. n is different than N.
Ex: If the input is:
n Nobody
the output is:
0
Your program must define and call the following method that
returns the number of times the input character appears in the
input string.
public static int countCharacters(char userChar, String
userString)
Note: This is a lab from a previous chapter that now requires the use of a method.
import java.util.Scanner; public class CountCharacters { public static int countCharacters(char userChar, String userString) { int count = 0; for(int i = 0; i < userString.length(); ++i) { if(userString.charAt(i)== userChar) { ++count; } } return count; } public static void main(String[] args) { Scanner in = new Scanner(System.in); char ch = in.next().charAt(0); String str = in.nextLine(); System.out.println(countCharacters(ch, str)); } }
Get Answers For Free
Most questions answered within 1 hours.