[英]How to display minimum and maximum values out of a list?
I need to display the minimum and maximum current Prices out of the list but I could only display the number at the end 我需要显示列表中的最小和最大当前价格,但我只能在结尾显示该数字
public StockPrice() {
char startChar = 'A';
String tmpSymbol = null;
int startPrice = 0;
int priceRightNow = 0;
for (int idx = 0; idx < MAX_STOCKS; ++idx) {
tmpSymbol = "" + (char) (startChar + idx) + (char) (startChar + idx + 1) + (char) (startChar + idx + 2);
startPrice = ThreadLocalRandom.current().nextInt(minStockPrice, maxStockPrice + 1);
priceRightNow = ThreadLocalRandom.current().nextInt(minStockPrice, maxStockPrice + 1);
myStocks[idx] = new Stock(tmpSymbol, startPrice, priceRightNow);
System.out.println(myStocks[idx]);
System.out.println();
}
int[] val = {priceRightNow};
List<Integer> myStocks = new ArrayList<Integer>();
for (Integer number : val ) {
myStocks.add(number);
}
System.out.println("The current lowest stock price is " + tmpSymbol +Collections.min(myStocks));
System.out.println("The current highest stock price is "+ tmpSymbol +Collections.max(myStocks));
}
You're overriding your variable.. collections.min, max should get your min, max values out of list. 你要覆盖你的变量.. collections.min,max应该从列表中获取你的最小值,最大值。
public class Test {
public static void main(String args[]) {
ArrayList<Integer> integerList = new ArrayList<>();
integerList.add(10);
integerList.add(1);
integerList.add(12);
System.out.println("MIN : "+Collections.min(integerList));
System.out.println("MAX : "+Collections.max(integerList));
}
}
this sample code will get you below output. 此示例代码将使您获得低于输出。
MIN : 1
MAX : 12
Your val
array contains the last priceRightNow
. 你的val
数组包含最后的priceRightNow
。 Everything you do in the previous loop iterations is irrelevant. 您在之前的循环迭代中所做的一切都无关紧要。 Then the call to ArrayList
creates a new empty list and you add the (only) value of val
in that list. 然后调用ArrayList
创建一个新的空列表,并在该列表中添加val
的(唯一)值。 The max and the min of that list is thus the last priceRightNow
因此,该列表的最大值和最小值是最后的priceRightNow
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.