这是我的代码。我在我的排序和打印方法中不断获得nullpointerexception,它从带有allAnimals.length的for循环开始。我认为在类中的数组allAnimal并没有按要求填充getData。 getData方法中的allAnimal在类中不被视为allAnimal。基本上所有其他方法仍然认为allAnimal为null。我不是Java的高手,所以如果有人可以告诉我如何解决此错误,或者给我有关如何避免该错误的提示,我将不胜感激。
public class Animal {
//data fields
private String name;
private int birthYear;
private String species;
private float balance;
private String ownersName;
static Animal[] allAnimal;
public Animal(){
//no-arg constructor
}
public Animal(String name, int birthYear, String species, float balance, String ownersName){
// constructor builds animal template
this.name = name;
this.birthYear = birthYear;
this.species = species;
this.balance = balance;
this.ownersName = ownersName;
}
//set and get for name
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
//set and get for birth year
public int getBirthYear() {
return birthYear;
}
public void setBirthYear(int birthYear) {
this.birthYear = birthYear;
}
//set and get for species
public String getSpecies() {
return species;
}
public void setSpecies(String species) {
this.species = species;
}
//set and get for balance
public float getBalance() {
return balance;
}
public void setBalance(float balance) {
this.balance = balance;
}
//set and get for owner
public String getOwnersName() {
return ownersName;
}
public void setOwnersName(String ownersName) {
this.ownersName = ownersName;
}
public static void getData(){
System.out.println("How many animals are in this report? ");
Scanner kb = new Scanner(System.in);
int length = kb.nextInt();
Animal[] allAnimal = new Animal[length];
System.out.println("input: animal name, birth year, species, bill balance and owner's name.");
//fill array of objects with data
int i;
for(i = 0; i < allAnimal.length; i++){
allAnimal[i] = new Animal(kb.next(), kb.nextInt(), kb.next(), kb.nextFloat(), kb.next());
}
}//end getData
public static void sortData(Animal[] allAnimal){
Animal temp;
int i,j;
for(i = 0; i < allAnimal.length; i++){
for(j = i + 1; j < allAnimal.length; j++){
if(allAnimal[i].getBalance() > allAnimal[j].getBalance() ){ //swap big with small
temp = allAnimal[j];
allAnimal[j] = allAnimal[i];
allAnimal[i] = temp;
}
}
}
}//end sortData
public static void printData(Animal[] allAnimal){
int i;
for(i = 0; i < allAnimal.length; i++){
System.out.println("Pet Name: " + allAnimal[i].getName() + " Birth year: " +
allAnimal[i].getBirthYear() + " Species: " + allAnimal[i].getSpecies() +
" Balance due: " + allAnimal[i].getBalance() + " Owner: " + allAnimal[i].getOwnersName());
}
}
public static void main(String[] args){
getData();
sortData(allAnimal);
printData(allAnimal);
}//end main
}//end class
最佳答案
您有两个名为allAnimal
的变量:
static Animal[] allAnimal;
Animal[] allAnimal = new Animal[length];
您初始化一个,然后使用另一个(仍为
null
)。在
getData()
中,更改Animal[] allAnimal = new Animal[length];
至
allAnimal = new Animal[length];
可能还有其他问题,我看起来不太仔细。