[英]Finds method only in main void (cannot find symbol, symbol: method tulosta(), location: class Object)
因此,問題在於方法“ print()”只能在main void中使用。 當我嘗試在“ changeAccount()”中使用它時,它說“找不到符號”。
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();
}
}
現在,這里是調用打印方法的地方。
public class Account {
public void print(){
}
}
在changeAccount
方法,參數accountList
被聲明為ArrayList
,不ArrayList<Account>
,所以類型accountList.get(0)
將java.lang.Object
,其不具有print()
定義的方法。
您的問題是從accountList.get(0)
返回的類型在您的兩個方法中是不同的。
在您的main
方法中,您已將accountList
定義為ArrayList<Account>
:
public static void main(String[] args) {
ArrayList<Account> accountList = new ArrayList<>(0);
...
}
因此,當您調用accountList.get(0)
,您將獲得一個Account
,並且可以在其上運行print()
而不會出錯。
在你changeAccount
方法,您已經定義了accountList
參數為原料的ArrayList:
public static int changeAccount(ArrayList accountList) {
...
}
所以,當你調用accountList.get(0)
你會得到一個Object
回來,它沒有print()
方法。
將參數的類型更改為ArrayList<Account>
:
public static int changeAccount(ArrayList<Account> accountList) {
//This should now work
accountList.get(0).print();
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.