繁体   English   中英

在比较带有嵌套循环的字符串数组时出现问题

[英]Problem comparing arrays of Strings with nested loops

这是我要解决的问题:我有两个字符串数组(“ matches”和“ visibleObjects”)。 我想搜索数组“ matches”中的所有单词,以查看数组“ visibleObjects”中是否至少有一个单词。 如果满足此条件,则这次我想再次搜索“匹配”中的单词,以从数组“ actionWords”中查找至少一个单词。 这就是我所拥有的,其中“ testDir”只是一个打印出来的调试字符串:

protected void Action(){
        boolean actionWord = false;
        String target = null;

        testDir = "first stage";
        firstLoop:
        for(String word : matches)
        {
            testDir += " " + word;
            for(String hint : visibleObjects)
            {
                testDir += " " + hint;
                if(word.equals(hint))
                {
                    target = word; //found a matching word
                    testDir = "Hint found";
                    break firstLoop;
                }
            }
        }

        if(target != null)
        {
            testDir = "stage two";

            secondLoop:
            for(String word : matches)
            {
                for(String action : actionWords)
                {
                    if(word.equals(action))
                    {
                        actionWord = true; //found one word from the actionWords array
                        testDir = "Acion OK";
                        break secondLoop;
                    }
                }
            }
        }


        if(actionWord){
            testDir = target;
            performAction(target);
        } 
    }

我所打印的只是数组匹配的第一个单词,而数组visibleObject的所有单词都匹配一次,因此它不会超过第二个循环。

这个代码正确吗? 任何人都可以发现该错误吗?

谢谢你的帮助!

您在第一个比赛中停止了外循环( break firstLoop; )-我认为那不是您想要的,是吗?

而是执行以下操作之一:

  1. 继续外循环而不是停止它( continue firstLoop;
  2. break;内循环( break;

该代码对我来说似乎很好:

public static void main(String[] args)
{
    String[] matches = { "a", "b", "c" };
    String[] visibleObjects = { "c", "d", "e" };
    String target = null;

    firstLoop: for (String word : matches)
    {
        for (String hint : visibleObjects)
        {
            if (word.equals(hint))
            {
                target = word;
                break firstLoop;
            }
        }
    }

    System.out.println(target);
}

这将打印出c 如果没有匹配项,则将输出null

请注意,您还可以使用一个循环和List.contains(...)方法,如下所示

List<String> l = Arrays.asList(visbleObjects)

for (String word : matches)
{
    if (l.contains(word))
    {
          target = word;
          break;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM