Mohammad Taha Mohammad Taha - 5 months ago 14
Java Question

A java program to find out the frequrncy of a word using Scanner class

Can any one tell me that how to use Scanner Class of Java to find the frequency of a word in a sentence.

I am confused as to enter a line in java i have to use nextInt() function but to compare need it to convert in char so how to do so.

For example:-

I enter on terminal window(Giving Input)

This is my cat.

Now i have to find the FREGUENCY of word "this" in the above sentence. Please can you give me some idea.REMEMBER THE RESTRICTION IMPOSED ON IT IS I HAVE TO USE ONLY SCANNER CLASS OF JAVA LIBRARY

PROGRAMME USING STREAM READER IS AS FOLLOWS-

import java.io.*;

class FrequencyCount
{

public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter the String: ");
String s=br.readLine();
System.out.println("Enter substring: ");
String sub=br.readLine();

int ind,count=0;
for(int i=0; i+sub.length()<=s.length(); i++)
//i+sub.length() is used to reduce comparisions
{
ind=s.indexOf(sub,i);
if(ind>=0)
{
count++;
i=ind;
ind=-1;
}
}
System.out.println("Occurence of '"+sub+"' in String is "+count);
}
}

Answer

alternative solution using pattern

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JavaApplication20 {

   public static void main(String [] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter a sentence:\t");
    String sentence = scanner.nextLine();
    System.out.print("Enter a word:\t");
    String word = scanner.nextLine();

    Pattern p = Pattern.compile(word);
    Matcher m = p.matcher(sentence);
    int count = 0;
    while (m.find()){
        count +=1;
    }    
    System.out.println("in your sentence the frequency of \""+word+"\" is:\t" + count);      
   }    
}