当我尝试调用方法compute()时遇到错误,我无法找出原因。我对java很新,我很可能没有采用正确的方法。我调用该方法时得到的错误是“无法对类型为Person的非静态方法计算(Person [])进行静态引用”
非常感谢任何帮助,谢谢。
import java.util.*;
public class Person {
private String name;
private int age;
public Person(String name, int age){
this.age = age;
this.name = name;
}
public int getAge(){
return age;
}
public double compute(Person[] family){ //computes the average age of the members in the array
double averageAge=0;
int ct = family.length;
for(Person k : family){
averageAge += k.getAge();
}
averageAge /= ct;
return averageAge;
}
public static void main(String[] args) {
int count;
double avg;
System.out.println("How many people are in your family?");
Scanner sc = new Scanner(System.in);
count = sc.nextInt();
Person[] family = new Person[count]; //creates an array of Persons
for (int i = 0; i<count; i++){
System.out.printf("Please enter the first name followed by age for person %d\n", i+1);
String personName = sc.next();
int personAge = sc.nextInt();
family[i] = new Person(personName, personAge); //fills array with Persons
}
avg = compute(family); //Error occurs here
for (int k = 0; k<count; k++){
System.out.printf("\nName: %s, Age: %d\n", family[k].name, family[k].age);
}
System.out.printf("Average age: %d\n", avg);
sc.close();
}
}
答案 0 :(得分:0)
您在静态方法中调用实例方法compute
。您应该创建Person的实例来调用方法或使其成为静态。