Make FileReader read every fourth line with a loop

2019-09-17 10:32发布

问题:

My problems is that I have to arrange, when searching for a customer, arrange the while loop to only examine every fourth line read.

This is the code I already have on this problem:

BufferedReader br = new BufferedReader(new FileReader("Customers.txt"));
String line;

while ((line = br.readLine()) != null)
{
    ...
}

br.close();

Does anybody know what needs to be at the place of "..."?

Thanks!

回答1:

Just call br.readLine() 3 times at the end of the loop, discarding the output:

BufferedReader br = new BufferedReader(new FileReader("Customers.txt"));
String line;

while ((line = br.readLine()) != null)
{
    ...
    for(int i=0;i<3;i++){ br.readLine(); }
}

br.close();


回答2:

Something along the lines of

int i = 0;
while ((line = br.readLine()) != null)
{
   i++;
   if (i % 4 == 0)
   {
      // if i is divisible by 4, then
      // your actual code will get executed
      ...
   }

}


回答3:

BufferedReader br = new BufferedReader(new FileReader("Customers.txt"));
String line;
int count 0;
while ((line = br.readLine()) != null)
{
    if (count!=3)
        count++;
    else {
        // Do something?
        count=0;
    }

}

br.close();