尝试从文件中读取并计算与数组中的单词匹配的短语数



我正在尝试读取用户给出的文件。 程序应扫描文件并计算文档中与我在数组中列出的单词匹配的单词数。 当我运行我的程序时,它卡在我的 while 循环中,我不确定为什么会发生这种情况。 有人能为我指出正确的方向吗?

package pkgfinal.nhammer2;

import java.nio.file.Files;
import java.util.Scanner;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FinalNhammer2 {
// Phishing Phrases
private static final String[] phishingPhrases = {"label", "invoice", "post",
"document", "postal", "calculations", "copy", "fedex", "statement",
"financial", "dhl", "usps", "8", "notification", "n", "irs", "ups", 
"no", "delivery", "ticket", "express", "shipment", "international",
"parcel", "confirmation", "alert", "report", "idnotification", "shipping",
"ssn"
};
private static final int phrasePoints[] = {3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 3,
2, 2, 3, 2, 2, 3, 2, 3, 2, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1
};

public static void main(String[] args) {
Scanner file = new Scanner(System.in);
int count = 0;
int numberOfPhrases = 30;
System.out.print("Enter file name: ");
Path path = Paths.get(file.nextLine());
if (Files.exists(path)) {
System.out.printf("%n%s exists%n", path.getFileName());
for (int i = 0; i < numberOfPhrases; i++){
while(file.hasNext()){
String word = file.next();
if (word.equalsIgnoreCase(phishingPhrases[i])){
count++;
}                    
}
}
System.out.printf("File has %d phishing phrases", count);
}
else{
System.out.printf("%s does not exist.", path);
}
}
}

解决代码中的以下问题:

  1. 为文件创建新Scanner
  2. 交换循环序列。

按如下方式操作:

int count = 0;
int numberOfPhrases = 30;
Scanner in = new Scanner(System.in);
System.out.print("Enter file name: ");
String fileName = in.nextLine();
File fileObj = new File(fileName);
if (fileObj.exists()) {
System.out.println("File exists");
Scanner file = new Scanner(fileObj);
while (file.hasNext()) {
String word = file.next();
for (int i = 0; i < phishingPhrases.length; i++) {
if (word.equalsIgnoreCase(phishingPhrases[i])) {
count++;
}
}
}
file.close();
System.out.printf("File has %d phishing phrases", count);
} else {
System.out.println("File does not exist");
}

最新更新