Comparing the strings in two different arraylists

☆樱花仙子☆ 提交于 2019-12-11 04:52:28

问题


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:

  1. The first list is an ArrayList of the Ship objects (a field on my game controller class)
  2. 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!


回答1:


Okay, I blew it. I'm still new to using the debugger and I should have gone there first, but I'm so used to having errors in my code that I assumed that was the problem and that there was something about arraylists that I wasn't understanding.

After debugging, I realized that I wasn't actually adding the ships until the end of the method that was calling this method - so, as you guys pointed out, there weren't any objects in the arraylists yet. It was very easy to see my problem once I had this direction.

Thanks everyone!



来源:https://stackoverflow.com/questions/20914224/comparing-the-strings-in-two-different-arraylists

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!