Loop Keyword Program Homework

前端 未结 3 1350
长发绾君心
长发绾君心 2020-12-12 08:13

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

相关标签:
3条回答
  • 2020-12-12 08:47

    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.

    0 讨论(0)
  • 2020-12-12 08:50

    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.

    0 讨论(0)
  • 2020-12-12 09:01
    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();
        }
    }
    
    0 讨论(0)
提交回复
热议问题