2011-09-23 127 views
0

这是我想解决的问题:我有两个字符串数组(“匹配”和“可视对象”)。我想搜索数组“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一次,所以它不会通过第二个循环....

此编码是正确的?任何人都可以发现错误?

感谢您的帮助!

回答

0

的代码似乎工作对我很好:

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

Thi s打印出c。如果你没有匹配,它会打印null

注意,你也可以使用一个循环和List.contains(...)方法,这样

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

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

你说得对,代码是正确的。我正在测试Android VoiceRecogniser的功能。事实证明,所有识别的单词实际上都是作为一个长条目输入到matches []中,而不是一系列字符串,这就是为什么for循环不能正常工作....我在字符串I上使用“contains”方法从匹配[]数组创建,它工作正常....感谢您的输入! – Alex

0

你在第一场比赛中停止外环(break firstLoop;) - 我想这不是你想要的,是吗?

而是执行下列操作之一:

  1. 继续而不是停止它的外环(continue firstLoop;
  2. 断裂内环唯一的(break;