Gustaffson

Java Code MOOC part 6 - 8

Sep 15th, 2025
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.59 KB | Source Code | 0 0
  1. public Item heaviestItem(){
  2.     //If no items are in the ArrayList<Item>, then return null.
  3.     if(this.items.isEmpty()){
  4.         return null;
  5.     }
  6.     //Create new object with first item in Arraylist<Item>
  7.     Item heaviestItem = new Item(this.items.get(0).getName(), this.items.get(0).getWeight());
  8.  
  9.     //Go through all the items in the Arraylist<Item> and find the heaviest one.
  10.     for (Item item:this.items){
  11.         if(heaviestItem.getWeight()<item.getWeight()){
  12.             heaviestItem = new Item(item.getName(), item.getWeight());
  13.         }
  14.     }
  15.     return heaviestItem;
  16. }
Tags: Java MOOC
Advertisement
Add Comment
Please, Sign In to add comment