String programs part 4
Write a program to input a sentence and print the frequency of the double occurrence characters.
Write a program to input a sentence and print the frequency of the double occurrence characters.
import java.io.*;
class DoubleOccur
{
public static void main()throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a sentence");
String str= br.readLine();
int len=str.length();
int count=0;
for (int i=0;i<len-1;i++)
{
char ch=str.charAt(i);
char ch1=str.charAt(i+1);
if(ch==ch1)
count++;
}
System.out.println("The frequency of the double occurrence is"+count);
}
}Output:-
I am good
The frequency of the double occurrence is: 1
Write a program to input a sentence and a word and print the frequency of the word in a sentence.
import java.io.*;
class WordFrequency
{
public static void main()throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a sentence");
String str= br.readLine().trim() + " "; // extra space so the last word is also counted
System.out.println("Enter a word to check for the frequency");
String wrd= br.readLine().trim();
int len=str.length();
int d=0; int count=0;
for (int i=0;i<len;i++)
{
char ch=str.charAt(i);
if(Character.isWhitespace(ch))
{
String temp=str.substring(d,i);
d=i+1; // the next word starts after the space
if(temp.equalsIgnoreCase(wrd))
count++;
}
}
System.out.println("The frequency of the word is "+count);
}
}Output:-
Enter a sentence
This is a school
Enter a word
school
The frequency of the word is 1
Related Posts
Continue learning with these related articles
Sum of First n Natural Numbers in Java (Loop and Formula)
Find the sum of the first n natural numbers in Java with a for loop, a while loop and the formula n(n + 1)/2, with a dry run and the sums of even numbers, odd numbers, squares and cubes.
Prime Number Program in Java: Check a Number and Print Primes in a Range
Check whether a number is prime in Java by counting its factors, a faster square-root method with isPrime(), and a program that prints all prime numbers in a range.

Encapsulation, Access Specifiers and Scope of Variables in Java for ICSE Class 10
ICSE Class 10 Computer Applications notes on encapsulation: private, default, protected and public access, data hiding with getter and setter methods, instance vs static (class) variables, local variables and scope, with a solved BankAccount program.