正确使用while循环中的BufferedReader.readLine() [英] Using BufferedReader.readLine() in a while loop properly

查看:407
本文介绍了正确使用while循环中的BufferedReader.readLine()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在阅读文本文件到我的程序时遇到了问题。以下是代码:

So I'm having an issue reading a text file into my program. Here is the code:

     try{
        InputStream fis=new FileInputStream(targetsFile);
        BufferedReader br=new BufferedReader(new InputStreamReader(fis));

        //while(br.readLine()!=null){
        for(int i=0;i<100;i++){
            String[] words=br.readLine().split(" ");
            int targetX=Integer.parseInt(words[0]);
            int targetY=Integer.parseInt(words[1]);
            int targetW=Integer.parseInt(words[2]);
            int targetH=Integer.parseInt(words[3]);
            int targetHits=Integer.parseInt(words[4]);
            Target a=new Target(targetX, targetY, targetW, targetH, targetHits);
            targets.add(a);
        }
        br.close();
    }
    catch(Exception e){
        System.err.println("Error: Target File Cannot Be Read");
    }

我正在读取的文件是100行参数。如果我使用for循环它完美地工作。如果我使用while语句(for循环上方注释掉的那个),它会在50处停止。用户有可能使用任意行数的文件运行程序,因此我当前的for循环实现赢了工作。

The file I am reading from is 100 lines of arguments. If I use a for loop it works perfectly. If I use the while statement (the one commented out above the for loop) it stops at 50. There is a possibility that a user can run the program with a file that has any number of lines, so my current for loop implementation won't work.

为什么行而(br.readLine()!= null)止在50?我检查了文本文件,没有任何东西可以挂起它。

Why does the line while(br.readLine()!=null) stop at 50? I checked the text file and there is nothing that would hang it up.

当我使用while循环时,我没有从try-catch中得到任何错误所以我我很难过。任何人都有任何想法吗?

I don't get any errors from the try-catch when I use the while loop so I am stumped. Anyone have any ideas?

推荐答案

你正在调用 br.readLine()第二次在循环中。

因此,每次你去的时候,你最终都会读到两条行。

You're calling br.readLine() a second time inside the loop.
Therefore, you end up reading two lines each time you go around.

这篇关于正确使用while循环中的BufferedReader.readLine()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆