对不起,我需要详细说明。
我正在使用Java编写简单的array
记录3次股票购买;发起的每辆新车都作为新交易提出:
~~ 1股当时购买100美元/股。
每股200美元购买2股。
每股300美元/股时购买3股。
手中共有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);
}
答案 0 :(得分:0)
好吧,试着猜猜你想要什么,这就是我想到的:
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);
}
}
对这样的静态方法有逻辑并不是一个好主意,但我不确定这是否是你想知道的。