Make FileReader read every fourth line with a loop

☆樱花仙子☆ 提交于 2019-12-25 02:31:49

问题


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


来源:https://stackoverflow.com/questions/9589689/make-filereader-read-every-fourth-line-with-a-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!