简体   繁体   中英

java outer while loop is not iterating

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

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

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();

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM