In this short article I would like to share with you a sample program that I called Occurrence of the Word Program in Java. What does the program will do is to allow the user to enter a sentence that has a repetitive words and then our program will ask the user what word to be search and count its number of occurrence and then our program will count the number of times a certain word appears in a given sentence by our user.
If you have some questions please send me an email at jakerpomperada@yahoo.com and jakerpomperada@gmail.com. People here in the Philippines who wish to contact me can reach me at my mobile number 09173084360.
Program Listing
import java.util.Scanner;
class count_words {
public static int find_words(String string, String substr) {
int a=0;
int second_string = 0;
int count = 0;
do {
a = string.indexOf(substr,second_string);
if (a != -1) count++;
second_string = a+substr.length();
} while(a != -1);
return count;
}
public static void main (String[] args ){
Scanner in = new Scanner(System.in);
String str1,str2,str3,str4;
System.out.println("==============================================");
System.out.println("|| OCCURENCE OF THE WORD PROGRAM ||");
System.out.println("==============================================");
System.out.print("\n");
System.out.println("Enter a Sentence : ");
System.out.print("\n");
str1 = in.nextLine();
str3 = str1.toUpperCase();
System.out.print("\n");
System.out.print("Enter a word to count : ");
str2 = in.nextLine();
str4 = str2.toUpperCase();
System.out.println("\n");
System.out.println("The number of occurrence in the word : " + str4 + " is "
+ find_words(str3,str4 ) + ".");
System.out.println("\n");
}
}
No comments:
Post a Comment