In: Computer Science
In java P4.6 Following Section 4.9 develop a program that reads text and displays the average number of words in each sentence. Assume words are separated by spaces, and a sentence ends when a word ends in a period. Start small and just print the first word. Then print the first two words. Then print all words in the first sentence. Then print the number of words in the first sentence. Then print the number of words in the first two sentences. Then print the average number of words in the first two sentences. At this time, you should have gathered enough experience that you can complete the program.
Here is the code for the above problem with output snippet. I have directly calculated the average number of words in a sentence. If you need further assistance please let me know.
// import Scanner class for input
import java.util.Scanner;
public class HelloWorld{
public static void main(String []args){
// Scanner class object for taking input with spaces
Scanner in = new Scanner(System.in);
// takes the input from the user
String str = in.nextLine();
System.out.println(str);
// have space counter and period counter initialized to zero
int space_count = 0;
int per_count = 0;
// for loop till the end of the input string
for(int i=0; i<str.length(); i++)
{
// count number of spaces
if(str.charAt(i) == ' ')
space_count++;
// count the number of periods
if(str.charAt(i) == '.')
per_count++;
}
// print the average number of words = total words/ total sentences
System.out.printf("Average number of words per sentence are : %d", (space_count+1)/per_count);
}
}
Here is the output snippet of the code