JSON_Derulo
JSON_Derulo

Reputation: 992

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;
    }

}

Upvotes: 0

Views: 818

Answers (3)

uğur taş
uğur taş

Reputation: 365

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.

Upvotes: 1

Anderson Oliveira
Anderson Oliveira

Reputation: 483

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.

Upvotes: 1

Silvan
Silvan

Reputation: 425

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.

Upvotes: 2

Related Questions