gpt4 book ai didi

java - 出现 "non static method cannot be referenced from a static context"错误的问题

转载 作者:行者123 更新时间:2023-12-01 23:58:57 25 4
gpt4 key购买 nike

我在尝试编写一个列出特定类中所有名称的方法时遇到此错误。 (底部错误)我尝试了一些东西,但对于我的生活,无法弄清楚。请帮忙,谢谢。

猫类:

public class Cat
{
// instance variables
private String name;
private int yearOfBirth;
private int weightInKilos;

public Cat() {
setName("");
setYearOfBirth(0);
setWeightInKilos(0);
}

/**
*
*/
public Cat(String newName, int newYearOfBirth, int newWieghtInKilos )
{
setName(newName);
setYearOfBirth(newYearOfBirth);
setWeightInKilos(newWieghtInKilos);
}


public String getName(){
return name;
}

public int getYearOfBirth(){
return yearOfBirth;
}

public int getWieghtInKilos(){
return weightInKilos;
}



public void setName(String newName){
if (newName != null ){
name = newName;
}
else{
System.out.println("Invalid Name");
}

}

public void setYearOfBirth(int newYearOfBirth){
if (yearOfBirth >= 0){
yearOfBirth = newYearOfBirth;
}
else{
System.out.println("Year Of Birth must not be negative!");
}
}

public void setWeightInKilos(int newWeightInKilos){
if (weightInKilos >= 0){
weightInKilos = newWeightInKilos;
}
else{
System.out.println("Weight must not be negative!");
}

}

}

类猫舍:

import java.util.ArrayList;


public class Cattery
{
// instance variables - replace the example below with your own
private ArrayList <Cat> cats;
private String businessName;

/**
* Constructor for objects of class Cattery
*/
public Cattery(String NewBusinessName)
{
cats = new ArrayList <Cat>();
NewBusinessName = businessName;
}

public void addCat(Cat newCat){

cats.add(newCat);
}

public void indexDisplay(int index) {
if((index >= 0) && (index <= cats.size()-1)) {
System.out.println(index);
}
else{
System.out.println("Invalid index position!");
}
}

public void removeCat(int indexremove){
if((indexremove >= 0) && (indexremove <= cats.size()-1)) {
cats.remove(indexremove);
}
else{
System.out.println("Invalid index position!");
}
}

public void displayNames(){
System.out.println("The current guests in Puss in Boots Cattery:");
for(Cat catNames : cats ){
System.out.println(Cat.getName()); //ERROR; non static method cannot be referenced from a static context..wtf

}
}
}

请帮忙,谢谢

最佳答案

当您有实例方法时,您需要在类的特定实例上调用它。

这里:

System.out.println(Cat.getName());

您正在尝试在 Cat 本身上调用它。你想要:

for (Cat cat : cats ) {
System.out.println(cat.getName());
}

请注意,我也将迭代变量的名称从 catNames 更改为 cat - 因为该值只是对“我们正在处理的猫”的引用就目前而言”。这不是猫的名字,也不是多只猫(或猫的名字)——它是一只猫。仔细命名变量非常重要 - 它可以帮助纠正代码看起来正确,以及帮助错误代码看起来不正确。对名为 catNames 的变量调用 getName() 没有任何意义...(名称集合的名称是什么?)但它在名为 cat 的变量上调用它绝对是有意义的。

原始代码中的另一个警告是 for 循环的主体没有使用迭代变量 - 这几乎总是表明出现了问题。当然,固定版本可以。

关于java - 出现 "non static method cannot be referenced from a static context"错误的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15197321/

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