gpt4 book ai didi

java - 如何在Java中搜索对象数组中的实例变量数组?

转载 作者:太空宇宙 更新时间:2023-11-04 11:34:29 25 4
gpt4 key购买 nike

我试图搜索实例变量数组,看看它是否包含对象数组内的变量。

现在,当实例变量数组包含我正在搜索的单词时,我可以获得返回“true” boolean 值的方法,但是当实例变量数组不包含该单词时,什么也不会发生。程序永远不会结束。

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

最佳答案

索引仅在一种情况下递增,无论哪种方式,您都需要递增它,以便在找不到时搜索移动到下一个字典对象

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

关于java - 如何在Java中搜索对象数组中的实例变量数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43435498/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com