琴弦在两个不同的ArrayList比较 [英] Comparing the strings in two different arraylists

查看:161
本文介绍了琴弦在两个不同的ArrayList比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于我自学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. 第一个列表是船舶对象的ArrayList(在我的游戏控制器类中的字段)

  2. 第二个名单是一个字符串(例如A5,B17等)的形式位置的ArrayList(这是我的船对象的字段)

我的检查,看有没有船,我要加入到船舶对象的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船舶领域的ArrayList(用我的主要方法)。而shipLocation是一个保存位置船舶对象的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!

推荐答案

好吧,我搞砸了。我还是新来使用调试器,我应该首先去那里,但我习惯了在我的code,我认为这是问题,有错误,有一些事我没的ArrayList ŧ理解。

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.

调试后,我意识到,我并没有实际添加的船只,直到被调用这个方法的方法结束 - 所以,正如你们所指出的,有没有在任何的ArrayList对象呢。这是很容易看到我的问题,一旦我有这个方向发展。

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.

谢谢大家!

这篇关于琴弦在两个不同的ArrayList比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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