gpt4 book ai didi

interface - 静态上下文错误中使用的非静态方法

转载 作者:行者123 更新时间:2023-12-02 11:05:46 25 4
gpt4 key购买 nike

关于静态上下文中使用的非静态方法的这段代码,我不断收到两个错误。此代码使用鸟、猫和狗的不同对象的 ArrayList,并使用名为 Pet 的接口(interface)将它们放入名为 petList 的 ArrayList 中。
我在第 4 行和第 6 行遇到相同的错误。

    public static void Feed(ArrayList petList){
Scanner input = new Scanner(System.in);
String petName = input.next();
contains(petName, petList);

if(ifThere == true){
String feed = Pet.feed();
System.out.println(petName + feed);
}
else{
System.out.println("Unknown pet");
}
}


public boolean contains (String petName, ArrayList petList){

boolean ifThere = false;
int sizeList = petList.size() -1;
for(int i=0; sizeList > i; i++){
Pet booleanPet = petList.get(i);
String booleanName = booleanPet.getName();
if (booleanName.equals(petName)){
ifThere = true;
}
}
return ifThere;

}

最佳答案

简而言之:您不能从静态方法调用非静态方法。

解决方案: 1)将您的“包含”方法设为静态,它将解决问题。

或者
2)(假设类的名称是 Pet 然后创建 Pet 类的实例并调用 contains 方法:
您的第 4 行可以替换为以下代码(C# 样式代码):

Pet somePet = new Pet ();
somePet.contains(petName, petList);

-- 额外细节:
静态方法是一种从不特定于任何对象的方法。例如添加2个数字。你
不需要实例化任何类来调用 Math.Add() 方法,因为 Add 是静态方法。

您也可以说 Static 是一种方法,它不是您肯定知道的虚拟含义
正在调用哪个方法。

关于interface - 静态上下文错误中使用的非静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13212687/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com