简体   繁体   中英

Can't remember how to do this for some reason

This one should be fairly simple I think, I just can't remember how, when using get methods of an object, how to pull the highest double out of the pack and put it in the println.

So far I just get every object to print with its percentages. But for the life of me I just can't remember and I know I've done this before.

public void displayBookWithBiggestPercentageMarkup(){
    Collection<Book> books  = getCollectionOfItems();
    Iterator<Book> it = books.iterator();

  while(it.hasNext()){
      Book b = it.next();
      double percent = b.getSuggestedRetailPriceDollars() / b.getManufacturingPriceDollars() * 100.0;
      System.out.println("Highest markup is " + percent + " " + b.getTitle() + " " + b.getAuthor().getName().getLastName());
    }   
}

I'm pretty sure I need another local variable but I can't seem to do anything but make it equal the other percent. I have removed the other variable for now as I try to think about it.

I won't go into a lot of detail because it's homework (well done for being up-front about that, by the way) but here's the key idea: keep track of the largest percentage you've seen so far as your loop runs. That's what you want in your other variable.

Good job posting what you've tried so far. You were on the right track. As you loop through your books, keep a variables continuously updated with the highest percent seen so far and another variable for the associated book. Output the variable at the end outside the loop after iteration is done. Also, don't forget to check the edge case of an empty list of books! Something like this should do the trick:

public void displayBookWithBiggestPercentageMarkup(){
    Collection<Book> books  = getCollectionOfItems();
  if (books.size() == 0) {
      return;
  }

  Iterator<Book> it = books.iterator();

  double highestPercent = 0;
  Book highestPercentBook = null;
  while(it.hasNext()){
      Book b = it.next();

      double percent = b.getSuggestedRetailPriceDollars() / b.getManufacturingPriceDollars() * 100.0;

      if (percent > highestPercent) {
          highestPercent = percent;
          highestPercentBook = b;
      }
   }    
   System.out.println("Highest markup is " + highestPercent
       + " " + highestPercentBook.getTitle()
       + " " + highestPercentBook.getAuthor().getName().getLastName());    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM