简体   繁体   English

创建 object 时找不到符号错误

[英]Cannot Find Symbol Error when creating an object

I am creating an ArrayList object that contains a class.我正在创建一个包含 class 的 ArrayList object。 However, when I call a method from the WordList() class, it says "error: cannot find symbol obj.numWordsOfLength(2)"但是,当我从 WordList() class 调用方法时,它显示“错误:找不到符号 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);当你调用obj.numWordsOfLength(2); you're calling the method numWordsOfLength from ArrayList (which does not exist), not from your WordList class.您正在从 ArrayList(不存在)调用方法numWordsOfLength ,而不是从您的WordList class 调用方法。

First of all, you are adding String to ArrayList, not you're WordList object.首先,您将字符串添加到 ArrayList,而不是 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
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 创建对象时如何解决“错误:找不到符号”? - How to fix “Error: Cannot find symbol” when creating an object? 从 class 创建新的 object 时出现“找不到符号”错误? - 'Cannot find symbol' Error when creating a new object from a class? 创建对象实例时出现“找不到符号”错误 - "Cannot find symbol" error when creating an instance of an object 创建对象并调用方法时出错,错误:找不到符号 - Error creating an object and calling a method, error: cannot find symbol 在创建新的类对象时,另一个“找不到符号”错误 - Yet another 'cannot find symbol' error when creating a new class object 创建对象时为什么会出现“找不到符号”错误? - Why am I getting a “cannot find symbol” error when creating an object? 使用继承在IO类中创建对象时找不到符号 - Cannot find symbol when creating an object in IO class using inheritance 初始化和定义对象后找不到符号错误 - Cannot find symbol error for object when it has been initialised and defined 声明新的午餐包对象时出现“错误:找不到符号”? - 'error: cannot find symbol' when declaring a new lunchBag object? 将对象转换为子类型时找不到符号 - cannot find symbol when casting an object to a subtype
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM