I'm working on a school assignment and i ran into some trouble. Basically I have an array of objects with a String name attribute, I want to search through that array with a keyword, and pick out any of the objects with that word and store it into another array. I can only use an array, and not arraylist or treemaps, etc. I get a problem where it only gets one of the objects and not the others, the keyword is "is".
this what I have so far:
import java.util.Arrays;
public class TesterTwo
{
public static void main(String[] args)
{
TestObj t1 = new TestObj("Where is my house",1);
TestObj t2 = new TestObj("Canada is really cold",2);
TestObj t3 = new TestObj("It's a big world",3);
TestObj t4 = new TestObj("What is This",4);
TestObj t5 = new TestObj("I'm at home",5);
TestObj[] thingy = new TestObj[]{t1,t2,t3,t4,t5};
System.out.println("BEFORE");
for(int a = 0; a < thingy.length; a++)
{
System.out.println(thingy[a].getName());
}
TestObj [] searchResult = new TestObj[5];
for (int i = 0; i < thingy.length; i++)
{
if(thingy[i].getName().contains("is"))
{
int j = 0;
searchResult[j] = thingy[i];
j++;
}else{continue;}
}
thingy = searchResult;
System.out.println("After the search has gone through:");
System.out.println("");
for(int i = 0; i < thingy.length; i++){
if(thingy[i] == null){break;}
System.out.println(thingy[i].getName());
}
}
}
EDIT: I found out i was doing the loop wrong my bad. Here's my fix:
TestObj [] searchResult = new TestObj[thingy.length];
for (int i = 0, k=0; i < thingy.length; i++)
{
if(!thingy[i].getName().contains("is"))
{
continue;
}
searchResult[k++] = thingy[i];
}
thingy = searchResult;
The problem is in the scope of declared
jinteger variable. Now you have it declared inside of theforloop which makes the scope ofjavailable only for a single iteration. At the end of iteration thejvariable is removed and new iteration makes new one. Move the declaration ofjoutside of theforloop:Additionaly the whole
elsestatement is not needed because theifstatement is kinda last in the loop and if theifis false the loop will try to go to the next iteration.Edit:
The fix you provided has a bit of performance improvement than my original answer. Using second variable in the
forstatement makes it avaiable through all iterations and after the loop is finished the variable will be removed from memory, so to the sample I provide it would be: