0

I'm trying to find the smallest value in an array list(iList). The array list contains multiple items (InventoryItem) each with their own description, cost, etc. I need to find the smallest cost, and return the item that has the smallest cost. Also, I have to use a while loop and not a for. Here is my code so far:

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++; 
  }  

}
3
  • 1
    okay, and does this code do what you think it should? If not, why do you think it's not doing what you think you wrote? Commented Oct 2, 2014 at 1:20
  • It isn't returning the item that has the smallest cost. Commented Oct 2, 2014 at 1:25
  • remember to analyse your problem, and then write that out. If you need the lowest number, start with a "super high number" called "low", and then check "is element X lower? then set low to X". At the end of the run, you should know the lowest number. Need the item with the lowest number? Clearly we also need a "lowestitem" variable now that we can set in tandem. Commented Oct 2, 2014 at 1:48

1 Answer 1

4

This is pretty simple. Store the current lowest, iterate through, and if something is smaller, save that. At the end return the current smallest.

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;
}

If you need to use a while loop, then just use a disguised for loop ;)

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;
}
Sign up to request clarification or add additional context in comments.

5 Comments

You'd probably want the for loop to start with int i = 1, since index 0 is already taken care of in the initialization of smallest.
@misberner Yup. But really it makes almost no difference timewise. Will edit.
I need to use a while loop instead of a for.
@kb94 What about that?
@kb94 Glad to help! If an answer helped you, you can mark it as accepted to show that your question is resolved.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.