[英]Comparing the strings in two different arraylists
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. 在我自学Java的过程中,我一直在编写类似战舰的游戏,但是我的方法遇到了问题,即确保在创建新船时除非所有位置都不会添加它值是唯一的。
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: 我有两个ArrayLists:
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: 我检查要添加到Ship对象的ArrayList中的船只是否具有唯一位置的方法如下:
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). 因此,“ theShips”是GameController上我的Ships ArrayList字段(使用Main方法)。 And "shipLocation" is my ArrayList field on the Ship object that holds the locations. “ shipLocation”是我在Ship对象上保存位置的ArrayList字段。
My println() statement never runs, so for some reason I'm never getting the for loops going? 我的println()语句永远不会运行,因此由于某种原因我永远都无法获得for循环?
Thank you for any guidance or insight you can provide here! 感谢您提供的任何指导或见解!
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! 感谢大家!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.