0

I wrote the following code and the inner for loop works fine, but the outer loop does not iterate. Here is my code:

BufferedReader userfeatures = new BufferedReader(new FileReader("userFeatureVectorsTest.csv"));
BufferedReader itemfeatures = new BufferedReader(new FileReader("ItemFeatureVectorsTest.csv"));         

while ((Uline = userfeatures.readLine()) != null) 
{
    for (String Iline = itemfeatures.readLine(); Iline != null; Iline = itemfeatures.readLine()) 
    {           
         System.out.println(intersect(Uline, Iline).size()); 
         System.out.println(union(Uline, Iline).size());  
    }
}
userfeatures.close();
itemfeatures.close();

}

It finds the intersection and union of the first line of the first file with every line of the 2nd file and then it stops. However, I need to continue and repeat the same procedure for next lines of the first file. So, I think there is some problems related to my outer while loop, but I could not find what is the proble :| Could someone help me please? Thanks

2
  • 2
    i´d rather say that it is looping over and over and your for loop isn´t looping anymore since you already read thorugh itemfeatures and itemfeatures.readLine() returns null since you are already at the end of the file. Commented Dec 8, 2015 at 16:07
  • You could put the initialisation of itemFeatures inside the outer loop. Or you could read the contents of the second file once and cache the information you need. Commented Dec 8, 2015 at 16:07

2 Answers 2

1

itemfeatures has to be initialized just before for loop each time you read from userfeatures. Otherwise your itemfeatures is fully read after first while iteration

Sign up to request clarification or add additional context in comments.

Comments

1

As people stated, your for loop reads the second file entirely, so you have to read it again each time.

So re-create its Reader before the for loop, and also close it after the for loop.

To put it simply, each time you read one line from File 1, you have to open, read entirely, and close File 2 :

BufferedReader userfeatures = new BufferedReader(new FileReader("userFeatureVectorsTest.csv"));


while ((Uline = userfeatures.readLine()) != null) 
{

    BufferedReader itemfeatures = new BufferedReader(new FileReader("ItemFeatureVectorsTest.csv")); 

    for (String Iline = itemfeatures.readLine(); Iline != null; Iline = itemfeatures.readLine()) 
    {           
         System.out.println(intersect(Uline, Iline).size()); 
         System.out.println(union(Uline, Iline).size());  
    }

   itemfeatures.close();
}
userfeatures.close();

}

1 Comment

I just accepted the answer, but thanks a lot for the time and effort :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.