1
// Calculating term frequency
System.out.println("Please enter the required word :");
Scanner scan = new Scanner(System.in);
String word = scan.nextLine();
String[] array = word.split(" ");
int filename = 11;
String[] fileName = new String[filename];
int a = 0;
for (a = 0; a < filename; a++) {
try {
System.out.println("The word inputted is " + word);
File file = new File(
"C:\\Users\\user\\fypworkspace\\TextRenderer\\abc" + a
+ ".txt");
System.out.println(" _________________");
System.out.print("| File = abc" + a + ".txt | \t\t \n");
for (int i = 0; i < array.length; i++) {
int totalCount = 0;
int wordCount = 0;
Scanner s = new Scanner(file);
{
while (s.hasNext()) {
totalCount++;
if (s.next().equals(array[i]))
wordCount++;
}
System.out.print(array[i] + " ---> Word count = "
+ "\t\t " + "|" + wordCount + "|");
System.out.print(" Total count = " + "\t\t " + "|"
+ totalCount + "|");
System.out.printf(" Term Frequency = | %8.4f |",
(double) wordCount/totalCount);
System.out.println("\t ");
}
}
} catch (FileNotFoundException e) {
System.out.println("File is not found");
}
}
这是我的代码,用于计算包含文本的文本文件的字数,总词数和词频。问题是我需要访问for循环之外的变量wordcount和totalcount。但改变地方声明变量wordcount和totalcount也会改变结果,使其不准确。有人可以帮我处理变量,这样我可以得到准确的结果,并且还可以访问for循环之外的变量吗?变量范围问题