Java 如何查看文本文件中字符串数组中的单词出现的次数
所以我想扫描一个文本文件,找出数组中的单词在该文本文件中使用的总次数 使用我的代码,我只能找出在文本文件中找到数组中零位单词的次数。我想要数组中所有单词的总数Java 如何查看文本文件中字符串数组中的单词出现的次数,java,arrays,file,search,Java,Arrays,File,Search,所以我想扫描一个文本文件,找出数组中的单词在该文本文件中使用的总次数 使用我的代码,我只能找出在文本文件中找到数组中零位单词的次数。我想要数组中所有单词的总数 String[] arr = {"hello", "test", "example"}; File file = new File(example.txt); int wordCount = 0; Scanner scan = new Scanner(file); for(int i = 0; i<arr.length; i++
String[] arr = {"hello", "test", "example"};
File file = new File(example.txt);
int wordCount = 0;
Scanner scan = new Scanner(file);
for(int i = 0; i<arr.length; i++){
while (scan.hasNext()) {
if (scan.next().equals(arr[i])){
wordCount++;
}
}
}
System.out.println(wordCount);
在这里,我想要的结果是wordCount=9
相反,我上面代码的wordCount等于4(hello的数量在文本文件中声明)这里发生的事情是:在第一个循环中,到达文件的末尾,您只得到“hello”的计数。可以在每个循环的结束/开始处重新调整指向文件开始的指针
String[] arr = {"hello", "test", "example"};
File file = new File(example.txt);
int wordCount = 0;
for(int i = 0; i<arr.length; i++){
Scanner scan = new Scanner(file);
while (scan.hasNext()) {
if (scan.next().equals(arr[i])){
wordCount++;
}
}
}
System.out.println(wordCount);
字符串[]arr={“hello”,“test”,“example”};
File File=新文件(example.txt);
int字数=0;
对于(int i=0;i扫描文件中的行,然后扫描arr
以查找匹配项
try (Scanner scan = new Scanner(file)) {
while (scan.hasNext()) {
String next = scan.next()
for(int i = 0; i<arr.length; i++){
if (next.equals(arr[i])){
wordCount++;
}
}
}
}
try(扫描器扫描=新扫描器(文件)){
while(scan.hasNext()){
String next=scan.next()
对于(int i=0;i反向你的循环-也就是说,对于每一行,扫描arr
,而不是你正在做的,这基本上是相反的,除了,当你试图找到下一个匹配的单词时,你已经读过了文件的结尾可能我误解了你,但是当我做你尝试的事情时,我得到了一个运行时异常
try (Scanner scan = new Scanner(file)) {
while (scan.hasNext()) {
String next = scan.next()
for(int i = 0; i<arr.length; i++){
if (next.equals(arr[i])){
wordCount++;
}
}
}
}