我需要使用 ArrayLists 来计算文本文件中的单词并显示它们的频率。我想首先创建“Word”对象的ArrayList。从那时起我就不应该有任何问题。我遇到的问题是在将对象添加到列表时。我收到一条错误消息“ArrayList 类型中的方法 add(Word) 不适用于参数 (String)”
public ArrayList<Word> wordList = new ArrayList<Word>();
String fileName, word;
int counter;
Scanner reader = null;
Scanner scanner = new Scanner(System.in);
public void analyzeText() {
System.out.print("Please indicate the file that you would like to analyze (with the path included): ");
fileName = scanner.nextLine();
try {
reader = new Scanner(new FileInputStream(fileName));
}
catch(FileNotFoundException e) {
System.out.println("The file could not be found. The program will now exit.");
System.exit(0);
}
while (reader.hasNext()) {
word = reader.next().toLowerCase();
wordList.add(word);
counter++;
}
}
public class Word {
String value;
int frequency;
public Word(String v) {
value = v;
frequency = 1;
}
}
最佳答案
您需要添加一个Word对象而不是字符串:
word = reader.next().toLowerCase();
Word myNewWord = new Word(word); /*Generates a Word Object using your constructor*/
wordList.add(myNewWord);
counter++
希望有帮助。
关于java - 将 Java ArrayList 与自定义对象一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53423146/