It will ask the user for a keyword to search for. Then, it will ask the user to enter sentences over and over. The user can stop the process by typing “stop” instead of a sentence (which means, of course, that we can’t analyze the one word sentence ‘stop’, but that is OK). Once the user has finished entering the sentences, the program should display the following statistics:
- The total number of sentences entered
- The total number of sentences that contain the keyword
- The average starting position of the keyword in the sentences that contain the keyword.
Can somebody help me put this program together? For #3 we only do average position of the sentences that contain the keyword.
I have the loop part, and for #3 I'm guessing we would use indexOf. #2 inputString.contains(keyword) I'm guessing? Can somebody help me with 1-3 and putting them into a Java program? Thanks.
import java.util.Scanner;
public class Lab6Loops {
public static void main(String[] args) {
String keywordString;
String inputString;
Scanner keyboard = new Scanner (System.in);
int numofSentences = 0;
int numofKeyword = 0;
System.out.println ("Enter a keyword. We will search each sentence for this word.");
keywordString = keyboard.nextLine ();
System.out.println ("Please enter a sentence or type 'stop' to finish");
inputString = keyboard.nextLine ();
while( !inputString.equals ("stop"))
{
if(inputString.contains (inputString));
numofSentences = numofSentences + 1;
if(inputString.contains (keywordString));
numofKeyword = numofKeyword + 1;
System.out.println ("Enter a line of text or 'stop' to finish");
inputString = keyboard.nextLine();
}
System.out.println ("You entered " + numofSentences + " sentences");
System.out.println ("You have " + numofKeyword + "sentences that contain the keyword");
}
}
See Question&Answers more detail:os