如何统计数组的值?

How count the value of array?

对不起,我需要详细说明。

我正在使用Java写简单的array记录3次股票买入;启动的每辆新车都显示为新交易:

~~ 100 美元/股时购买的 1 股。

当时购买了 2 股 200 美元/股。

当时购买了 3 股 300 美元/股。

共6股在手。 ~~

如何计算每股平均买入价?通过不断添加新车不断 运行。

package javaex;

import java.util.ArrayList;
import java.util.function.Predicate;

    public class javaExstockprice
        public static void main(String[] args){
         ArrayList<Car> al= new ArrayList();
        al.add(new Car(1,100));
        al.add(new Car(2,200));
        al.add(new Car(3,300));

        System.out.println("showsharesbuyingmethod-alltransaction = shares : buying");
        al.forEach(c->c.showsharesbuying() );
        System.out.println();
        al.removeIf(c->c.shares>1);
        System.out.print("transcation amount 1 share / below");
        System.out.println();
         al.forEach(c->c.showsharesbuying() );
        System.out.println();
    }







    class Car
    float shares;
    float buying;
    Car (float a, float b) {
        shares = a;
        buying = b;
    }

    void showsharesbuying() {
        System.out.println("showsharesbuying " + shares+ " : " + buying);
    }

好吧,试着猜测你想要什么,这是我想到的:

import java.util.List;
import java.util.ArrayList;
import java.util.function.Predicate;

public class JavaExStockPrice {

    public static void main(String[] args){

        List<Car> al= new ArrayList();
        al.add(new Car(1,100));
        al.add(new Car(2,200));
        al.add(new Car(3,300));

        System.out.println("showsharesbuyingmethod-alltransaction = shares : buying");
        al.forEach(c->c.showSharesBuying() );
        System.out.println("Avg: " + priceAvg(al));
        System.out.println();
        al.removeIf(c->c.shares>1);
        System.out.print("transcation amount 1 share / below");
        System.out.println();
        al.forEach(c->c.showSharesBuying() );
        System.out.println("Avg: " + priceAvg(al));
        System.out.println();
    }

    static double priceAvg(List<Car> l) {
        return l.stream().mapToDouble(c -> c.buying * c.shares).average().getAsDouble() / 
                    l.stream().mapToDouble(c -> c.shares).average().getAsDouble();
    }

}



class Car {
    float shares;
    float buying;

    Car (float a, float b) {
        shares = a;
        buying = b;
    }

    void showSharesBuying() {
        System.out.println("showsharesbuying " + shares+ " : " + buying);
    }
}

像这样对静态方法进行逻辑处理并不是一个好主意,但我不确定这是否是您想知道的。