As I'm teaching myself Java, I've been programming a Battleship like game, but I've run into a problem with my method for making sure that when I create a new ship I don't add it unless all of its location values are unique.
I'm doing something wrong, because my method isn't working and I'm getting duplicate values (or ships that have the same location).
I have two ArrayLists:
- The first list is an ArrayList of the Ship objects (a field on my game controller class)
- The second list is an ArrayList of the Locations in the form of a String (e.g. A5, B17, etc.) (this is a field on my Ship object)
My method for checking to see if a ship I'm about to add to the ArrayList of Ship objects has unique locations is as follows:
private boolean hasUniqueLocs(Ship ship) {
for (Ship x : theShips) {
for (String y : ship.shipLocation) {
System.out.println("Checking to see if " + x.shipLocation + " ship contains this value: " + y);
if (x.shipLocation.contains(y)) {
return false;
}
}
}
return true;
}
So "theShips" is my ArrayList of Ships field on the GameController (with my Main method). And "shipLocation" is my ArrayList field on the Ship object that holds the locations.
My println() statement never runs, so for some reason I'm never getting the for loops going?
Thank you for any guidance or insight you can provide here!
hasUniqueLocs()or add a print statement at the beginning. Also - Maroun has a good point - if there aren't any locations you won't reach the print statement.theShipsandshipLocation?My println() statement never runsthen YES, you need to debug and see when the method is ever called. The logic here does not look like a problem, but you've wasted some time focusing the question this way