java - 将 Java ArrayList 与自定义对象一起使用

标签 java arraylist

我需要使用 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/

相关文章:

java - 为什么这会返回 null?

java - 防止将重复对象添加到 ArrayList 或 HashSet

Java:使用.txt文件将每行的特定索引分配给数组列表

c++ - 在 C++ 中创建 Person 对象的数组列表

java - 如何获取文件 io 的兼容时间戳?

java - 迭代 ToggleGroup 并设置每个 ToggleButton 的属性

java - 如何使用多个 yaml 文件生成 openAPI 代码

java - 新手帮助-Java货币计算器

java - 我的数组列表搜索方法有问题。条件仅在第一个索引中为真

Java arraylist 不兼容类型错误