【问题标题】:How to search an array of instance variables inside an array of objects in Java?如何在Java中的对象数组中搜索实例变量数组?
【发布时间】:2017-04-16 08:55:27
【问题描述】:

我正在尝试搜索实例变量数组以查看它是否包含对象数组中的变量。

现在,当实例变量数组包含我正在搜索的单词时,我可以获得返回“真”布尔值的方法,但是当实例变量数组不包含该单词时,什么也不会发生。节目永无止境。

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

【问题讨论】:

    标签: java arrays oop object logic


    【解决方案1】:

    索引仅在一种情况下增加,您需要以任何一种方式增加它,以便搜索移动到下一个字典对象以防找不到

         //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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-15
      • 1970-01-01
      相关资源
      最近更新 更多