Saturday 20 August 2016

Chapter 6 Exercise 23, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

*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 and displays the number of occurrences of the character in the string.

import java.util.Scanner;
 
public class ProgrammingExercise6_23 {
 
 public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
 
  System.out.print("Enter a string:");
  String s1 = input.nextLine();
  System.out.print("Enter a charecter:");
  char ch = input.nextLine().charAt(0);
 
  System.out.println("the number of " + ch + " in the string is "
    + count(s1, ch));
 
 }
 
 public static int count(String str, char a) {
  int count = 0;
 
  for (int i = 0; i < str.length(); i++) {
 
   if (str.charAt(i) == a)
    count++;
 
  }
 
  return count;
 
 }
 
}

1 comment :