这是一个非常简单的问题,但由于某种原因,我无法理解对象数组或对象数组。我所要做的就是接受 5 个用户输入,并创建一个名为 Height 的类,创建对象数组并将用户输入存储到 obj 数组中并打印平均值。我有点卡住了。
class Height{
int total=0;
int count=0;
public Height(int y) {
total=total+y;
count++;
}
public void print() {
System.out.print("The average is: "+total/count);
}
}
public class ObjectArray {
public static void main(String[] args){
Scanner s=new Scanner(System.in);
System.out.println("Enter 5 heights in inches: ");
int[] x=new int[5];
int total=0;
for(int i=0;i<x.length;i++) {
x[i]=s.nextInt();
}
Height[] h=new Height[x.length];
for(int y=0;y<x.length;y++) {
h[y]=new Height(x[y]);
}
h.print();
}
}
也许我把事情搞得太复杂了。现在的问题是我无法调用 h.print();。我尝试了不同的迭代,例如:取出打印方法并在每次迭代后进行所有打印。
最佳答案
你的做法是错误的。您的 Height
类似乎负责平均值的评估。因此,您应该将所有值放入单个 Height
实例中,而不是为每个用户值生成一个新实例。
但是,h
是 Height
对象的数组,而 print()
方法是在单个 Height< 上定义的
实例。为了调用该方法,您必须访问 h
中包含的对象之一,即 h[0].print()
。
关于java - 使用对象数组/对象数组求平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49387475/