Chapter VI Question 23 (Occurrences of a specified character)
*6.23 (Number of occurrences of specified characters) Use the following method header to write a method to find the number of occurrences of specified characters in a string. public static int count(String str, char a) For example, count("Welcome",'e') returns 2. Write a test program that prompts the user to enter a string and a character, and displays the number of times the character appears in the string. *6.23(Occurrences of a specified character)Write a method that finds the number of occurrences of a specified character in a string using the following header: public static int count(String str, char a) For example, count(“Welcome”, 'e') returns 2. Write a test program that prompts the user to enter a string followed by a character then displays the number of occurrences of the character in the string.
Reference Code:
package chapter06;import java.util.Scanner;publicclassCode_23{
publicstaticvoidmain(String[] args){
Scanner input =newScanner(System.in);
System.out.print("Enter a sring: ");
String str = input.nextLine();
System.out.print("Enter a character: ");char a = input.nextLine().charAt(0);
System.out.println("The times "+ a +" in "+ str +" is "+count(str,a));}publicstaticintcount(String str,char a){
int count =0;for(int i =0; i < str.length(); i++){
if(str.charAt(i)== a)
count++;}return count;}}
The results show that:
Enter a sring: Welcome
Enter a character: e
The times e in Welcome is 2
Process finished with exit code 0