How to search for a keyword in an array of objects and copy that object to another array

407 views Asked by At

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

There are 1 answers

2
itwasntme On BEST ANSWER

The problem is in the scope of declared j integer variable. Now you have it declared inside of the for loop which makes the scope of j available only for a single iteration. At the end of iteration the j variable is removed and new iteration makes new one. Move the declaration of j outside of the for loop:

int j =0;
for (int i = 0; i < thingy.length; i++) 
{
    if(thingy[i].getName().contains("is")) 
    {
        //...
    }
}

Additionaly the whole else statement is not needed because the if statement is kinda last in the loop and if the if is 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 for statement 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:

for (int i = 0, j =0; i < thingy.length; i++) { //...