你说“有一个家庭作业”所以我假设你已经完成了这个。
我会做的有点不同。String
首先,我认为您的数组中的某些关键字不正确。根据Wikipedia和Oracle,Java 有 50 个关键字。无论如何,我已经很好地评论了我的代码。这就是我想出的...
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
public class CountKeywords {
public static void main(String args[]) {
String[] theKeywords = { "abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "default", "do", "double", "else", "enum", "extends", "false", "final", "finally", "float", "for", "goto", "if", "implements", "import", "instanceof", "int", "interface", "long", "native", "new", "null", "package", "private", "protected", "public", "return", "short", "static", "strictfp", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "true", "try", "void", "volatile", "while" };
// put each keyword in the map with value 0
Map<String, Integer> theKeywordCount = new HashMap<String, Integer>();
for (String str : theKeywords) {
theKeywordCount.put(str, 0);
}
FileReader fr;
BufferedReader br;
File file = new File(args[0]);
// attempt to open and read file
try {
fr = new FileReader(file);
br = new BufferedReader(fr);
String sLine;
// read lines until reaching the end of the file
while ((sLine = br.readLine()) != null) {
// if an empty line was read
if (sLine.length() != 0) {
// extract the words from the current line in the file
if (theKeywordCount.containsKey(sLine)) {
theKeywordCount.put(sLine, theKeywordCount.get(sLine) + 1);
}
}
}
} catch (FileNotFoundException exception) {
// Unable to find file.
exception.printStackTrace();
} catch (IOException exception) {
// Unable to read line.
exception.printStackTrace();
} finally {
br.close();
}
// count how many times each keyword was encontered
int occurrences = 0;
for (Integer i : theKeywordCount.values()) {
occurrences += i;
}
System.out.println("\n\nTotal occurences in file: " + occurrences);
}
}
每次遇到文件中的关键字时,我首先检查它是否在 Map 中;如果不是,它不是一个有效的关键字;如果是,那么我更新与关键字关联的值,即,我将关联的值增加Integer
1,因为我们再次看到了这个关键字。
或者,您可以摆脱最后一个 for 循环并保持运行计数,这样您就可以...
if (theKeywordCount.containsKey(sLine)) {
occurrences++;
}
...最后打印出计数器。
我不知道这是否是最有效的方法,但我认为这是一个坚实的开始。
如果您有任何问题,请告诉我。我希望这有帮助。
赫里斯托