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 se
package console;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Console {
static float averagePositionInSentence = 0;
static String searchTerm = "";
static int noOfSentencesEntered = 0;
static int noOfMatches = 0;
public static void main(String[] args) {
searchTerm = writeToConsoleAndReturnInput("Add phrase to search for.");
writeToConsole("Now type some sentences. To exit type the word 'stop' on its own");
mainInputLoop();
outputResults();
}
public static void mainInputLoop() {
boolean ended = false;
while (!ended) {
try {
String input = readLineFromConsole();
if (!input.equalsIgnoreCase("stop")) {
maintainStatisticalData(input);
} else {
ended = true;
}
} catch (Exception e) {
writeToConsole("There was an error with your last input");
}
}
}
public static void outputResults() {
writeToConsole("You entered " + noOfSentencesEntered + " sentences of which " + noOfMatches + " conatined the search term '" + searchTerm + "'");
writeToConsole("");
writeToConsole("On average the search term was found at starting position " + (averagePositionInSentence / noOfSentencesEntered) + " in the sentence");
}
public static void maintainStatisticalData(String input) {
noOfSentencesEntered++;
if (input.contains(searchTerm)) {
noOfMatches++;
int position = input.indexOf(searchTerm)+1;
averagePositionInSentence += position;
}
}
//terminal helper methods
public static void writeToConsole(String message) {
System.out.println(message);
}
public static String writeToConsoleAndReturnInput(String message) {
System.out.println(message);
try {
return readLineFromConsole();
} catch (IOException e) {
//should do something here
return "Exception while reading line";
}
}
public static String readLineFromConsole() throws IOException {
InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(converter);
return in.readLine();
}
}