比较两个不同数组列表中的字符串 [英] Comparing the strings in two different arraylists

查看:54
本文介绍了比较两个不同数组列表中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我自学 Java 时,我一直在编写类似战舰的游戏,但我的方法遇到了问题,以确保在创建新船时我不会添加它,除非所有其位置值是唯一的.

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).

我有两个 ArrayList:

I have two ArrayLists:

  1. 第一个列表是 Ship 对象的 ArrayList(我的游戏控制器类中的一个字段)
  2. 第二个列表是一个字符串形式的 Locations ArrayList(例如 A5、B17 等)(这是我的 Ship 对象上的一个字段)

我用于检查我将要添加到 Ship 对象的 ArrayList 的船是否具有唯一位置的方法如下:

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;
}

所以theShips"是我在 GameController 上的 Ships 字段的 ArrayList(使用我的 Main 方法).shipLocation"是我保存位置的 Ship 对象上的 ArrayList 字段.

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.

我的 println() 语句永远不会运行,所以出于某种原因,我永远不会让 for 循环运行?

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!

推荐答案

好吧,我搞砸了.我对使用调试器还是个新手,我应该先去那里,但我已经习惯了我的代码中的错误,我认为这是问题所在,并且有一些关于数组列表的东西我不理解.

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.

调试后,我意识到在调用此方法的方法结束之前我实际上并没有添加船只 - 所以,正如你们所指出的,arraylists 中还没有任何对象.一旦我有了这个方向,就很容易看到我的问题.

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.

谢谢大家!

这篇关于比较两个不同数组列表中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆