【发布时间】:2021-09-14 20:53:33
【问题描述】:
我正在尝试编写一个读取文本文件并计算每个单词出现次数的 java 程序。但我不断收到没有这样的元素异常。我认为 ArrayList 或者我如何访问它的元素有问题。任何帮助将不胜感激。
package text_analyzer;
import java.io.File;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;
public class Text_analyzer
{
public static void main(String[] args) throws Exception
{
File file = new File("TestFile.txt");
Scanner sc = new Scanner(file);
int i = 0, indexOfWord = 0, count = 0;
List<String> words = new ArrayList<String>();
List<Integer> wordCount = new ArrayList<Integer>();
while (sc.hasNextLine())
{
String word = sc.next();
if(words.contains(word))
{
indexOfWord = words.indexOf(word);
count = wordCount.get(indexOfWord);
count = count+1;
wordCount.add(indexOfWord, count);
}
else
{
words.add(i,word);
wordCount.add(i,1);
i++;
}
}
sc.close();
int no_of_elements = words.size();
for(int j = 0; j < no_of_elements; j++)
System.out.println(words.get(j));
}
}
【问题讨论】:
-
如果你使用
hasNextLine,你应该使用nextLine,而不是next -
哇,立即工作。谢谢。
标签: java nosuchelementexception