如何从列表中显示最小值和最大值?

问题描述 投票:0回答:2

我需要显示列表中的最小和最大当前价格,但我只能在结尾显示该数字

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));
}
java arrays list max minimum
2个回答
0
投票

你要覆盖你的变量.. 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));

    }
}

此示例代码将使您获得低于输出。

MIN : 1
MAX : 12

0
投票

你的val数组包含最后一个priceRightNow。您在之前的循环迭代中所做的一切都无关紧要。然后调用ArrayList创建一个新的空列表,并在该列表中添加val的(唯一)值。因此,该列表的最大值和最小值是最后一个priceRightNow

© www.soinside.com 2019 - 2024. All rights reserved.