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)
Program
import java.util.Scanner;
public class Number {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String s = sc.nextLine();
System.out.print("Enter a character: ");
char ch = sc.next().charAt(0);
System.out.println("The number of occurrences of "+ ch + " in " + s + " is " + count(s,ch));
}
public static int count(String str, char ch) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ch)
count++;
}
return count;
}
}
Result:
Enter a string: hello
Enter a character: l
The number of occurrences of l in hello is 2
public static int count(String str, char a)
Program
import java.util.Scanner;
public class Number {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String s = sc.nextLine();
System.out.print("Enter a character: ");
char ch = sc.next().charAt(0);
System.out.println("The number of occurrences of "+ ch + " in " + s + " is " + count(s,ch));
}
public static int count(String str, char ch) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ch)
count++;
}
return count;
}
}
Result:
Enter a string: hello
Enter a character: l
The number of occurrences of l in hello is 2
No comments:
Post a Comment