1 回答
TA贡献1891条经验 获得超3个赞
制作一个共享分析器类,它封装了您想要的功能:
class ShareAnalyzer {
private final int[] aktiePris;
private int sellMinut = 0, buyMinut = 0, buyPrice, sellPrice;
ShareAnalyzer(int[] aktiePris) {
this.aktiePris = aktiePris;
findProfit();
}
private void findProfit() {
if (aktiePris.length < 1) return ;
int minValue = aktiePris[0];
int maxValue = minValue;
int indeksMaxMinut = 0, indeksMinMinut = 0;
for (int i = 1; i < aktiePris.length; i++) {
if (aktiePris[i] > maxValue) {
maxValue = aktiePris[i];
indeksMaxMinut = i;
int priceDiff = maxValue - minValue;
if (priceDiff > getProfit()) {
sellPrice = maxValue;
buyPrice = minValue;
sellMinut = indeksMaxMinut;
buyMinut = indeksMinMinut;
}
} else if (aktiePris[i] < minValue) {
minValue = maxValue = aktiePris[i];
indeksMinMinut = i;
}
}
}
//time in minutes from opening
int getSellTime() {return sellMinut;}
int getSellPrice() {return sellPrice;}
//time in minutes from opening
int getBuyTime() {return buyMinut; }
int getBuyPrice() {return buyPrice;}
int getProfit() { return sellPrice - buyPrice; }
}
您还可以添加一个打印共享分析器信息的方法:
//this could be implemented as `toString` of ShareAnalyzer
private static void printShareInfo(ShareAnalyzer shareAnalyzer){
System.out.println("Best time & price for buying is " + shareAnalyzer.getBuyTime() + " minutes after opening for " + shareAnalyzer.getBuyPrice() + " EUR." + "\n"
+ "Best time & price for selling is " + shareAnalyzer.getSellTime() + " minutes after opening for " + shareAnalyzer.getSellPrice() + " EUR." + "\n"
+ "Profit: " + shareAnalyzer.getProfit());
}
ShareAnalyzer为要分析的每个共享构建一个新实例。
public static void main(String args[]) {
int[] aktiePris1 = new int[]{10, 7, 5, 8, 11, 9};
ShareAnalyzer shareAnalyzer1 = new ShareAnalyzer(aktiePris1);
printShareInfo(shareAnalyzer1);
int[] aktiePris2 = new int[]{2, 12, 4, 7 , 11, 9, 1 , 8};
ShareAnalyzer shareAnalyzer2 = new ShareAnalyzer(aktiePris2);
printShareInfo(shareAnalyzer2);
}
您可以使用此链接运行代码并对其进行测试
添加回答
举报