简体   繁体   中英

Finds method only in main void (cannot find symbol, symbol: method tulosta(), location: class Object)

So the problem is that the method "print()" can be used only in main void. When i try to use it in "changeAccount()" it says "cannot find symbol".

public class Main {

    public static ArrayList createAccount(ArrayList accountList) {

        Account account1 = new Account();
        accountList.add(account1);
        return accountList;
    }

    public static int changeAccount(ArrayList accountList) {

        accountList.get(0).print();
    }

    public static void main(String[] args) {

        ArrayList<Account> accountList = new ArrayList<>(0);
        createAccount(tiliTaulukko);
        accountList.get(0).print();
    }
}

Now here is where print methos is called from.

public class Account {

    public void print(){

    }

}

changeAccount方法,参数accountList被声明为ArrayList ,不ArrayList<Account> ,所以类型accountList.get(0)java.lang.Object ,其不具有print()定义的方法。

Your problem is that the type returned from accountList.get(0) is not the same in your two methods.

In your main method, you have defined accountList as an ArrayList<Account> :

public static void main(String[] args) {
    ArrayList<Account> accountList = new ArrayList<>(0);
    ...
}

So when you call accountList.get(0) , you get an Account back, and can run print() on it without an error.

In your changeAccount method, you have defined the accountList parameter as a raw ArrayList:

public static int changeAccount(ArrayList accountList) {
    ...
}

So when you call accountList.get(0) , you get an Object back, which has no print() method.

Change the type of your parameter to be ArrayList<Account> :

public static int changeAccount(ArrayList<Account> accountList) {
    //This should now work
    accountList.get(0).print();
    ...
}

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