gpt4 book ai didi

java - 如何计算一个单词在 Java 文本文件中出现的次数?

转载 作者:行者123 更新时间:2023-12-03 23:14:54 24 4
gpt4 key购买 nike

所以我是 Java 的新手,我正在编写一个代码,该代码应该读取用户输入的 .txt 文件,然后要求用户输入要搜索的词在 .txt 文件中。我无法弄清楚如何计算输入的单词在 .txt 文件中出现的次数。相反,我的代码只计算代码显示的行数。谁能帮我弄清楚如何让我的程序计算单词出现的次数而不是单词显示的行数在吗?谢谢!这是代码:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class TextSearch {

public static void main(String[] args) throws FileNotFoundException {
Scanner txt;
File file = null;
String Default = "/eng/home/tylorkun/workspace/09.1/src/Sample.txt";

try {
txt = new Scanner(System.in);
System.out.print("Please enter the text file name or type 'Default' for a default file. ");
file = new File(txt.nextLine());

txt = new Scanner(file);

while (txt.hasNextLine()) {
String line = txt.nextLine();
System.out.println(line);
}
txt.close();
} catch (Exception ex) {
ex.printStackTrace();
}

try {
txt = new Scanner(file);
Scanner in = new Scanner(System.in);
in.nextLine();
System.out.print("Please enter a string to search for. Please do not enter a string longer than 16 characters. ");
String wordInput = in.nextLine();

//If too long
if (wordInput.length() > 16) {
System.out.println("Please do not enter a string longer than 16 characters. Try again. ");
wordInput = in.nextLine();
}

//Search
int count = 0;
while (txt.hasNextLine()) //Should txt be in?
{
String line = txt.nextLine();
count++;
if (line.contains(wordInput)) //count > 0
{
System.out.println("'" + wordInput + "' was found " + count + " times in this document. ");
break;
}
//else
//{
// System.out.println("Word was not found. ");
//}
}
} catch (FileNotFoundException e) {
System.out.println("Word was not found. ");
}
} //main ends
} //TextSearch ends

最佳答案

由于单词不必是独立的,您可以执行一个有趣的 for 循环来计算您的单词在每一行中出现的次数。

public static void main(String[] args) throws Exception {
String wordToSearch = "the";
String data = "the their father them therefore then";
int count = 0;
for (int index = data.indexOf(wordToSearch);
index != -1;
index = data.indexOf(wordToSearch, index + 1)) {
count++;
}

System.out.println(count);
}

结果:

6

因此您的代码的搜索部分可能如下所示:

//Search
int count = 0;
while (txt.hasNextLine())
{
String line = txt.nextLine();
for (int index = line.indexOf(wordInput);
index != -1;
index = line.indexOf(wordInput, index + 1)) {
count++;
}
}

System.out.println(count);

关于java - 如何计算一个单词在 Java 文本文件中出现的次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31665659/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com