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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…