Using BufferedReader.readLine() in a while loop properly

后端 未结 7 1621
无人共我
无人共我 2020-11-27 19:35

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

     try{
        InputStream fis=new FileInputStream(targetsFile);
        Bu         


        
7条回答
  •  醉梦人生
    2020-11-27 19:59

    Thank you to SLaks and jpm for their help. It was a pretty simple error that I simply did not see.

    As SLaks pointed out, br.readLine() was being called twice each loop which made the program only get half of the values. Here is the fixed code:

    try{
            InputStream fis=new FileInputStream(targetsFile);
            BufferedReader br=new BufferedReader(new InputStreamReader(fis));
            String words[]=new String[5];
            String line=null;
            while((line=br.readLine())!=null){
                words=line.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");
        }
    

    Thanks again! You guys are great!

提交回复
热议问题