Loop Keyword Program Homework

2019-01-20 20:25发布

问题:

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:

  1. The total number of sentences entered
  2. The total number of sentences that contain the keyword
  3. 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");
    }   
}

回答1:

I like having self-documenting code, so here are a couple suggestions for how you can have a nice tight main loop:

functional-ish semantics

public void loop() {
  // TODO: ask for the keyword and store it somewhere

  while(true) {
    try {
      updateStatistics(checkOutput(getSentence()));
    } catch (EndOfInput) {
      printStatistics();
    }
  }
}

Object-Oriented

public void loop() {
  String keyword = myPrompter.getNextSentence();
  myAnalyzer.setKeyword(keyword);

  while (true) {
    String sentence = myPrompter.getNextSentence();
    AnalysisResult result = myAnalyzer.analyze(sentence);
    if (result.isEndOfInput()) {
      myAnalyzer.printStatistics();
      return;
    }
  }
}

What both of these approaches gives you is a simple framework to plug in the specific logic. You could do all of it inside the main loop, but that can get confusing. Instead, it's preferable to have one function doing one task. One function runs the loop, another gets the input, another counts the # of sentences, etc.

Sometimes I'll start with those little functions, and build the app from the bottom-up, so I'd write a method that takes a string and returns true/false depending on if it's the string "stop". You can even write unit tests for that method, so that when you're building the rest of the app, you know that method does what you intended it to. It's nice to have lots of modular components that you can test along the way, rather than writing a huge long loop and wondering why it's not doing what you want.



回答2:

sounds like you need to prompt the user for an initial input then enter in to a loop that will last until the user presses stop (or whatever), in each iteration you need to prompt the user for a sentence, if the user inputs data increment one counter that stores the number of sentences, test the sentence against the keyword entered and increment a second counter as applicable, you will also need to push the position that the word occured in to a stack to later get the average which should be the sum of the stack divided by the size. you should be able to use indexOf() to get the position.



回答3:

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();
    }
}