KnowledgeBoat Logo

Computer Applications

Write a program to enter a sentence from the keyboard and count the number of times a particular word occurs in it. Display the frequency of the search word.

Sample Input:
Enter a sentence: The quick brown fox jumps over the lazy dog.
Enter a word to search: the

Sample Output:
Search word occurs 2 times

Java

Java String Handling

11 Likes

Answer

import java.util.Scanner;

public class KboatWordFrequency
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a sentence: ");
        String str = in.nextLine();
        System.out.print("Enter a word to search: ");
        String ipWord = in.nextLine();
        str += " ";
        String word = "";
        int count = 0;
        int len = str.length();

        for (int i = 0; i < len; i++) {
            if (str.charAt(i) == ' ') {

                if (word.equalsIgnoreCase(ipWord))
                    count++ ;

                word = "";
            }
            else {
                word += str.charAt(i);
            }
        }
        
        if (count > 0) {
            System.out.println("Search word occurs " + count + " times.");
        }
        else {
            System.out.println("Search word is not present in sentence.");
        }
        
    }
}

Output

BlueJ output of Write a program to enter a sentence from the keyboard and count the number of times a particular word occurs in it. Display the frequency of the search word. Sample Input: Enter a sentence: The quick brown fox jumps over the lazy dog. Enter a word to search: the Sample Output: Search word occurs 2 times

Answered By

6 Likes


Related Questions