[英]How do I count an occurence of a specific word in a txt file in Java?
我正在嘗試為“ list.txt”文檔中的特定單詞創建一個基本單詞計數器。 我現在使用的代碼不會掃描“ Customer”,即使“ Customer”已經在Word文檔中出現了幾次,我也嘗試用“ Customer”的值制作一個String變量,但這也沒有用,也許有人可以糾正我出了問題的地方嗎?
static int totalContracts() throws FileNotFoundException
{
Scanner scannerInput = new Scanner("list.txt");
int count = 0;
while (scannerInput.hasNext())
{
String nextWord = scannerInput.next();
System.out.println(nextWord);
if (nextWord.equals("Customer"))
{
count++;
}
}
return count;
}
您沒有打開文件。
Scanner scannerInput = new Scanner(new File("list.txt"));
如果您使用new Scanner("list.txt")
則只需掃描文本“ list.txt”。
您將String類型的參數傳遞給Scanner,其中Scanner僅會從該指定的String中產生值。
為了使掃描儀能夠從實際文件中生成值,您可以傳入定義文件路徑的File對象。
為此,您應該初始化一個新的File對象,並將其路徑傳遞給您要掃描的文件。 完成此操作后,即可將File對象傳遞給Scanner。
File file_to_scan = new File("list.txt");
Scanner scanner_input = new Scanner(file_to_scan);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.