Skip to content
Advertisement

Having trouble getting the .contains method to detect whether or not a ship is afloat

I want to check my ArrayList for ships that have sunk using the .contains method. 2 out of the 5 ships are supposed to be sunk but my code keeps bringing back all 5 as sunk.

I thought I could do it with a simple

if(fleetList.contains(data.isAfloat()) == false)

Is there is a method or something that I am missing? I can’t figure it out even after several google searches and re-reading of text.

public class ShipTest {
    public static void main(String[] args) {
        System.out.println("ARRAY OF SHIPS IN MAIN");
        Ship cs1 = new CruiseShip("Caribbean", 2700, true, 1998, "Magic");
        Ship cs2 = new CruiseShip("Atlantic Ocean", 1300, false, 1912, "Titanic");
        
        Ship cgs1 = new CargoShip("containers", 391, false, 1974, "El Faro");
        
        CargoShip cgs2 = new CargoShip("crude oil", 564763, false, 1979, "Seawise Giant");
        
        Ship ws1 = new WarShip("super carrier", "United States Navy", true, 1972, "USS Nimitz");
        
        Ship[] fleet = {cs1, cs2, cgs1, cgs2, ws1};
        for (int i = 0; i < fleet.length; i++)
        {
            System.out.println(fleet[i]);
        }
        
        List<Ship> fleetList = new ArrayList<Ship>();
        Collections.addAll(fleetList, fleet);
        
        shipShow(fleetList);
    }
    
    public static void shipShow(List<Ship> fleetList ) {
        System.out.println("ARRAY LIST OF SHIPS FROM METHOD");
        fleetList.remove(2);
        Ship ws2 = new WarShip("attack submarine", "United States Navy", true, 2015, "USS John Warner");
        fleetList.add(ws2);
        int sunk = 0;
        for (Ship data : fleetList) {
            System.out.println(data);
            if(fleetList.contains(data.isAfloat()) == true)
            {
                sunk += 1;
            }
        }
        System.out.println(sunk + " of these ships sank!");
    }
}

Advertisement

Answer

If you have a list of paintings you like, and I ask you: Hey, uh, are eggs on the list, you will probably answer “what the heck? This is a list of paintings, it’s not a grocery list.”

But there is a technical answer too: No, ‘eggs’ are (obviously) not on this list of paintings.

And that’s exactly how java works. No, data.isAfloat(), which is a boolean (true or false) is obviously not in the list of ships, no.

You’re already looping through ships (for (Ship data : fleetList)). There is no need to further refer to fleetList inside of that loop.

All you want is if (data.isAfloat()). (== true is not needed either. data.isAfloat() already returns a boolean value, it already returns true or false).

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement