[英]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;
)-我認為那不是您想要的,是嗎?
而是執行以下操作之一:
continue firstLoop;
) 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.