我正在使用計數器的while循環來查找數組上的元素。我將檢查如果返回的元素等於數組的長度,則找不到該元素。循環是這樣的。查找數組上的元素時,我應該做一個別的?
int i = 0;
int returned;
boolean found = false;
while(i < words.length && !found){
WordInText check = new WordInText(w);
if(check.equals(words[i])){
found = true;
}
else{
i++;
}
return i
什麼我不知道它是否會更好,而不是做一個對其他任何條件下做到以下幾點
int i = 0;
int returned;
boolean found = false;
while(i < words.length && !found){
WordInText check = new WordInText(w);
if(check.equals(words[i])){
found = true;
}
i++;
}
if(!found)
i++;
return i-1
我覺得,因爲它沒有第二個是更有效檢查每個循環的條件,如果數組非常長,則必須進行很多操作。但我不確定什麼時候決定每一個,因爲第二個看起來真是醜陋而不直觀。
更好的方法是使用'HashSet'。 –
什麼是'w ','WordInText'? – user1803551
我問他們是什麼,你說「是」... – user1803551