我遇到此錯誤的問題,同時試圖編寫一個方法,列出特定類中的所有名稱。 (在底部的錯誤)我已經嘗試了一些事情,但對於我的生活,無法弄清楚。請幫忙,謝謝。問題與「非靜態方法不能從靜態上下文引用」錯誤
類貓:
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
}
}
}
請幫幫忙,謝謝
謝謝你的工作,現在我明白了。我有另一個問題。我的公共無效indexDisplay不起作用。我希望它打印出我的其他類的名稱,而不是打印出我設置的參數。我認爲我需要讓'索引'等於某件事,但我也遇到了麻煩。有什麼建議麼? – 2013-03-04 08:40:58
@JoshuaBaker:如果你有另一個問題,你應該問*作爲另一個問題 - 理想情況下用一個簡短但完整的程序*只顯示問題。 – 2013-03-04 08:41:49