Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用数组参数调用方法时发生Java错误_Java_Arrays_Oop_User Defined Types_Method Call - Fatal编程技术网

使用数组参数调用方法时发生Java错误

使用数组参数调用方法时发生Java错误,java,arrays,oop,user-defined-types,method-call,Java,Arrays,Oop,User Defined Types,Method Call,我尝试调用compute()方法时出错,我无法找出原因。我对java相当陌生,很可能我做的事情不正确。调用该方法时出现的错误是“无法从Person类型对非静态方法compute(Person[])进行静态引用” 任何帮助都将不胜感激,谢谢 import java.util.*; public class Person { private String name; private int age; public Person(String name, int age

我尝试调用compute()方法时出错,我无法找出原因。我对java相当陌生,很可能我做的事情不正确。调用该方法时出现的错误是“无法从Person类型对非静态方法compute(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();
}
import java.util.*;
公共阶层人士{
私有字符串名称;
私人互联网;
公众人物(字符串名称,整数年龄){
这个。年龄=年龄;
this.name=名称;
}
公共整数getAge(){
回归年龄;
}
public double compute(Person[]family){//计算数组中成员的平均年龄
双平均值=0;
int ct=族长度;
(k人:家庭){
averageAge+=k.getAge();
}
平均值/=ct;
平均回报率;
}
公共静态void main(字符串[]args){
整数计数;
双平均值;
System.out.println(“你家有多少人?”);
扫描仪sc=新的扫描仪(System.in);
计数=sc.nextInt();
Person[]family=新的Person[count];//创建一个Person数组

对于(int i=0;i您正在静态方法中调用实例方法
compute
。您应该创建Person实例来调用该方法,或者将其设置为静态