【问题标题】:How to display minimum and maximum values out of a list?如何显示列表中的最小值和最大值?
【发布时间】:2019-09-20 09:47:16
【问题描述】:

我需要在列表中显示当前最低和最高价格,但我只能在最后显示数字

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


【解决方案1】:

您正在覆盖您的变量.. 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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2012-01-19
      • 1970-01-01
      • 1970-01-01
      • 2018-03-05
      • 1970-01-01
      • 2020-09-22
      • 2021-01-13
      • 1970-01-01
      • 2013-08-25
      相关资源
      最近更新 更多