Java调用带有数组参数的方法时出错

Java Error when calling a method with an array parameter

我在尝试调用方法 compute() 时遇到错误,我无法弄清楚原因。我是 java 的新手,很可能我没有以正确的方式做某事。调用该方法时出现的错误是 "Cannot make a static reference to the non-static method compute(Person[]) from the type 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();
}

}

您正在静态方法中调用实例方法 compute。您应该创建一个 Person 的实例来调用该方法,或者将其设为静态。