I'm having an error when I try to call a method compute() and I cannot figure out why. I am fairly new to java and it is very possible that I am not doing something the correct way. The error I get when I call the method is "Cannot make a static reference to the non-static method compute(Person[]) from the type Person"
Any help would be much appreciated, thank you.
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();
}
}
You're calling the instance method compute
inside a static method. You should either create an instance of Person to call the method or make it static.