2017-04-16 35 views
1

我試圖搜索實例變量的數組,以查看它是否包含一個變量,該變量位於對象數組內。如何搜索Java中的對象數組內的實例變量數組?

現在我能得到的方法時,實例變量數組包含我正在尋找的字返回一個「真」布爾值,但是當實例變量的數組不包含這個詞,什麼都不會發生。該計劃永遠不會結束。

//array of objects (lets assume it is filled with words) 
    Dictionary[] dictionary 

    String output = "word was "; 
    if (search(dictionary) { 
     output += "found"; 
    } 
    else { 
     output += " not found"; 
    }   

    System.out.println(output); 

搜索方法

public static boolean search(Dictionary[] dictionary) { 
    boolean found = false; 
    String word = "Apples"; 
    int index = 0; 

//first create a loop tho go through all objects until found or no more objects 
    while (index < dictionary.length && !found) { 

    //check if Dictionary is a thesaurus or bilingual Dictionary 
    if (dictionary[index] instanceof Bilingual) { 

     //downcast that object 
     Bilingual aDictionary = (Bilingual)dictionary[index]; 

     //get the array of instance variables for that a specific object at the index 
     String[] words = aDictionary.getAllWords(); 

     int x = 0; 

     //now go through the array & check if it contains the word 
     while(x < words.length && !found) { 
      if (words[x].equalsIgnoreCase(word)) { 
       found = true; 
      } 
      else { 
       //go to next word 
       x++; 
      } 
     } 
    } 
    else { 
     //go to next dictionary object 
     index++; 
    } 
    }     
    return found; 
} 

回答

0

該指數只有在一種情況下增加,你需要或者增加它的方式,以便在情況下,搜索移動到下一個字典對象沒有找到

 //first create a loop tho go through all objects until found or no more objects 
while (index < dictionary.length && !found) { 

//check if Dictionary is a thesaurus or bilingual Dictionary 
if (dictionary[index] instanceof Bilingual) { 

    //downcast that object 
    Bilingual aDictionary = (Bilingual)dictionary[index]; 

    //get the array of instance variables for that a specific object at the index 
    String[] words = aDictionary.getAllWords(); 

    int x = 0; 

    //now go through the array & check if it contains the word 
    while(x < words.length && !found) { 
     if (words[x].equalsIgnoreCase(word)) { 
      found = true; 
     } 
     else { 
      //go to next word 
      x++; 
     } 
    } 
} 

    //go to next dictionary object 
    index++; 

}     
return found;