简体   繁体   中英

Cannot Find Symbol Error when creating an object

I am creating an ArrayList object that contains a class. However, when I call a method from the WordList() class, it says "error: cannot find symbol obj.numWordsOfLength(2)"

import java.util.ArrayList;

public class WordList{

    public static void main(String []args){
        ArrayList obj = new ArrayList<WordList>();
        obj.add("bird");
        obj.add("wizard");
        obj.add("to");
        obj.numWordsOfLength(2);
     }


    private ArrayList<String> myList;

    public WordList(){
        myList = new ArrayList<String>();
    }

    public int numWordsOfLength(int len){
    //Code
    }

    public void removeWordsOfLength(int len){
    //Code
    }

 }

When you call obj.numWordsOfLength(2); you're calling the method numWordsOfLength from ArrayList (which does not exist), not from your WordList class.

First of all, you are adding String to ArrayList, not you're WordList object.

I think what you're trying to achieve will look more like this:

public class WordList {
    private List<String> wordList = new ArrayList<>();

    public static void main(String[] args) {
        WordList wordList = new WordList();
        wordList.add("bird");
        wordList.add("wizard");
        wordList.add("to");
        wordList.numWordsOfLength(2);
    }

    public void add(String word) {
        wordList.add(word);
    }

    public int numWordsOfLength(int len) {
        //Code
    }

    public void removeWordsOfLength(int len) {
        //Code
    }
}

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