简体   繁体   English

使用对象数组/对象数组查找平均值

[英]Find Average using Array of Objects/Object Array

this is such a simple problem but for some reason, I cant wrap my head around Array of Objects or Object Arrays. 这是一个非常简单的问题,但是由于某种原因,我无法将对象包裹在对象数组或对象数组上。 All I have to do is take in 5 user inputs, and create a class called Height, create object array and store user inputs into obj array and print the average. 我所要做的就是吸收5个用户输入,并创建一个名为Height的类,创建对象数组并将用户输入存储到obj数组中,并打印平均值。 I'm kinda stuck. 我有点卡住了。

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();
    }
}

Maybe I'm over complicating it. 也许我已经使它复杂化了。 The problem right now is that I cannot invoke h.print();. 现在的问题是我无法调用h.print();。 I've tried different iterations, ex: taking out the print method and doing all the printing after every iteration. 我尝试了不同的迭代,例如:取出打印方法并在每次迭代后进行所有打印。

Your approach is wrong. 您的方法是错误的。 Your Height class appears to be responsible for the evaluation of the mean value. 您的Height班级似乎负责评估平均值。 Hence, you should put all values inside a single Height instance, instead of generating a new instance for each user value. 因此,您应该将所有值放在单个Height实例中,而不是为每个用户值生成一个新实例。

However, h is an array of Height s object, while print() method is defined on a single Height instance. 但是, h是一个Height对象的数组,而print()方法是在单个Height实例上定义的。 In order to call such method, you have to access one of the objects contained in h , that is h[0].print() . 为了调用这种方法,您必须访问h包含的对象之一,即h[0].print()

I'm assuming that your goal is simply to print the average of all the heights recieved via user input. 我假设您的目标只是打印通过用户输入获得的所有高度的平均值。

Your code in your main method is a tad confusing, so correct me if I'm wrong in any of the examples I give here. 您的main方法中的代码有点令人困惑,因此,如果在此处给出的任何示例中有错误,请更正我。 You should, instead of creating the x[] array, simply add the user input for the five values to Height.total in a for loop, and increase the Height.count variable by one each loop through. 您应该(而不是创建x[]数组),只需在for循环中将五个值的用户输入添加到Height.total并在每次循环中将Height.count变量增加一。 This should look something like this: 看起来应该像这样:

for (int i = 1; i <= 5; i++) {
    // System.out.println("Please enter the next height: ");
    Height.total += s.nextDouble();
    Height.count++;
}

Then, you can run Height.print(); 然后,您可以运行Height.print(); .

I would also recommend adding a System.out.print(""); 我还建议添加System.out.print(""); command to let the user know that they should enter the next value. 命令让用户知道他们应该输入下一个值。 That's the comment I left in the example code I gave above. 这就是我在上面给出的示例代码中留下的注释。

You have to design your Height in a way that match your requirement : 您必须按照自己的要求设计Height

  • you need different Height with for each one a value 您需要不同的Height ,每个Height都需要一个值
  • you need to know how many instances there is 您需要知道有多少个实例

For that, you need a private value, and a static counter : 为此,您需要一个私有值和一个静态计数器:

class Height {

    private int value = 0;

    private static int count = 0;    // static => nb of instances

    public Height(int y) {
        value = y;
        count++;
    }

    public static int averageOf(Height... heights) {
        return Arrays.stream(heights).mapToInt(h -> h.value).sum() / count;
    }
}

To get the average, because it doesn't depend on a particular instance, you can have a static method, that sums all the value of the Height given and divide by the nb of instance 要获得平均值,因为它不依赖于特定实例,您可以有一个静态方法,该方法将所有给定的Height值相加并除以实例的nb

And use like : 并使用像:

public static void main(String[] args) {
    Scanner s = new Scanner(System.in);
    int nb = 5;
    System.out.println("Enter " + nb + " heights in inches: ");

    Height[] heights = new Height[nb];
    for (int i = 0; i < heights.length; i++) {
        heights[i] = new Height(Integer.parseInt(s.nextLine()));
    }

    System.out.println("Average is " + Height.averageOf(heights));
}

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); } }

you see the constructor ? 你看到构造函数了吗?

Every time you invoke that it will create a new object. 每次调用它都会创建一个新对象。 and print() can be called on only one Height object. print()只能在一个Height对象上调用。

Rethink about how to create Height object. 重新考虑如何创建Height对象。 You don't need an array. 您不需要数组。

You could do something like below , create a method called update that updates your variables in the class Height . 您可以执行以下操作,创建一个名为update的方法来更新Height类中的变量。 ( Note : think about renaming this class also may be AverageHeight .) (注意:考虑重命名此类也可以是AverageHeight 。)

class Height{ int total=0; int count=0; public void update(int y) { total=total+y; count++; } public void print() { System.out.print("The average is: "+total/count); } }

Then in your main() : 然后在您的main()

Instead of : Height[] h=new Height[x.length]; for(int y=0;y<x.length;y++) { h[y]=new Height(x[y]); } 代替: Height[] h=new Height[x.length]; for(int y=0;y<x.length;y++) { h[y]=new Height(x[y]); } Height[] h=new Height[x.length]; for(int y=0;y<x.length;y++) { h[y]=new Height(x[y]); }

Do this : 做这个 :

Height h=new Height(); for(int y=0;y<x.length;y++) { h.update( x[y] ); } h.print();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM