简体   繁体   中英

Using Java ArrayList with custom objects

I need to use ArrayLists to count the words in a text file and display their frequency. I would like to start by creating the ArrayList of "Word" objects. From that point I shouldn't have an issue. The problem I am encountering is when adding an object to the list. I receive an error stating "The method add(Word) in the type ArrayList is not applicable for the arguments (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;
    }

}

You need to add a Word Object not a String:

word = reader.next().toLowerCase();
Word myNewWord = new Word(word); /*Generates a Word Object using your constructor*/
wordList.add(myNewWord);
counter++

Hope that helps.

wordList is an array of "Word" objects. But in line 17

wordList.add(word);

you're adding another type of content into the array (a string).

Note there's an object-type, named "Word" (uppercase), and another variable named "word" (lowercase) of type string.

You're adding a string "word" to the array list, but in this case you can add only objects "Word" to the ArrayList of name wordList .

You need to add Word object to your list. But you are assigning a string which is readed from scanner. You need to create a Word object.

I think, your solution for counting word is wrong. You are using wrong data structure. Hashmap fits better for this case. You can assign words as a key and count of words as a value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM