簡體   English   中英

在數組列表中找到最小值

[英]Finding the smallest value in an array list

我正在嘗試在數組列表(iList)中找到最小值。 數組列表包含多個項目(InventoryItem),每個項目都有自己的描述,成本等。我需要找到最小的成本,並返回成本最小的項目。 另外,我必須使用while循環而不是for。 到目前為止,這是我的代碼:

public InventoryItem itemWithLowestCost() {

  int index = 0;
  double smallest = 0;

  while (index < iList.size()) {
     if (!(smallest < iList.get(index).getCost())) {
        smallest = iList.get(index).getCost();
     }

     if (iList.get(index).getCost() == smallest) {
        return //what to put here? ;
     }  

     index++; 
  }  

}

這很簡單。 存儲當前最低的值,進行迭代,如果較小,則保存該值。 最后返回當前的最小值。

public InventoryItem itemWithLowestCost() {

  InventoryItem smallest = iList.get(0);

  for (int i=1;i<iList.size();i++) {
    if(iList.get(i).getCost() < smallest.getCost()) {
      smallest = iList.get(i);
    }
  }

  return smallest;
}

如果需要使用while循環,則只需使用偽裝的for循環;)

public InventoryItem itemWithLowestCost() {

  InventoryItem smallest = iList.get(0);

  int i = 1;
  while (i<iList.size()) {
    if(iList.get(i).getCost() < smallest.getCost()) {
      smallest = iList.get(i);
    }
    i++;
  }

  return smallest;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM