BufferedReader - Help!!!

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • brendanmcdonagh
    New Member
    • Nov 2007
    • 153

    BufferedReader - Help!!!

    Hi all,

    I'm struggling with a challenge on new learnings about reading and writing from a txt file.

    Now I have just learnt about the Scanner class and i can usedelimiter (",") to create tokens. But what if the txt file has a heading before each token on the first line, how do you check that what you want it to say and what it does say are true and therefore go on to next line which are where the tokens are. I do admit this is homework but i have spent a full day (which i haven't got) on one question. please somebody help me.

    Code:
     /**
        * Prompts the user for the name of the text file that 
        * contains the results of the teams in this pool. The
        * method uses this file to set the results of the teams.
        */
       public void loadTeams()
       {
           OUDialog.alert("Please Select a file containing results for : " + this.getPoolName());
           String pathName = OUFileChooser.getFilename();
           File aFile = new File(pathName);
           BufferedReader bufferedFileReader = null;
           try
           {
               Scanner lineScanner;
               bufferedFileReader = new BufferedReader(new FileReader(aFile);
               String currentLine = bufferedFileReader.readLine()
               if (currentLine.equals(this.getPoolName());
               {
                   currentLine = bufferedFileReader.newLine()
       }
    This is what i have managed so far but i know im wrong, my first confusion is how to get on to another line after the header is true.
    The second confusion is how to end program safely if false.
    This is all being done in a try catch finally statement .

    the txt file reads like this

    Pool A
    England,3,0,1,2 ,0
    Samoa,1,0,3,0,1
    South Africa,4,0,0,3, 0
    Tonga,2,0,2,0,1
    USA,0,0,4,0,1

    Any ideas??

    Brendan
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    BufferedReaders read more behind the scenes that you can know. Why not just
    read lines (using that BufferedReader) ? The first line is the pool name and the
    other lines are the score of the countries. A line simply is a String and it has a
    nice split() method available.

    Split the other lines around the comma; that method returns an array of Strings.
    The first element in that array is the name of the country. The other entries
    represent the scores that can be converted from a String to an int using a method
    from the Integer class (check out the API for the Integer class).

    You don't need a Scanner for this, most certainly not when combined with a
    BufferedReader object.

    kind regards,

    Jos

    Comment

    • brendanmcdonagh
      New Member
      • Nov 2007
      • 153

      #3
      Thanks for your advice - i was worried i would be advised to use other ways but i have to show that i have learnt what i was taught! But the textbooks are not too good at teaching!!

      here's my updated code, i am a little more confident with this but I am getting a ) expected compiler error.

      anyone see anything please??

      Any suggestions where to put the else statement and also what to put in it to end program safely if if statement is false?

      Code:
       /**
          * Prompts the user for the name of the text file that 
          * contains the results of the teams in this pool. The
          * method uses this file to set the results of the teams.
          */
         public void loadTeams()
         {
             OUDialog.alert("Please Select a file containing results for : " + this.getPoolName());
             String pathName = OUFileChooser.getFilename();
             File aFile = new File(pathName);
             BufferedReader bufferedFileReader = null;
             try
             {
                 Scanner lineScanner;
                 bufferedFileReader = new BufferedReader(new FileReader(aFile));
                 String whichPool = bufferedFileReader.readLine();
                 if(whichPool.equals(this.getPoolName())
                 {
                     String currentLine = bufferedFileReader.readLine();
                     while(currentLine != null)
                     {
                                                  
                  lineScanner = new Scanner(currentLine);
                  lineScanner.useDelimiter(",");
                  Team aTeam =  new Team(lineScanner.next());
                  aTeam.setWon(lineScanner.next());
                  aTeam.setDrawn(lineScanner.next());
                  aTeam.setLost(lineScanner.next());
                  aTeam.setFourOrMoreTries(lineScanner.next());
                  aTeam.setSevenPointsOrLess(lineScanner.next());
                  aTeam.setTotalPoints(aTeam.calculateTotalPoints());
                  currentLine = bufferedFileReader.readLine();
              }
          }
      }
      catch(Exception anException)
      {
      System.out.println("Error: " + anException);
      }
      finally
      {
      try
      {
      bufferedFileReader.close();
      }
                  
      catch(Exception anException)
      {
      System.out.println("Error: " + anException);
      }           
       }          
       
         }
      Last edited by brendanmcdonagh; Aug 11 '08, 07:12 PM. Reason: missed a couple of ; which aen't the problem

      Comment

      • JosAH
        Recognized Expert MVP
        • Mar 2007
        • 11453

        #4
        Originally posted by brendanmcdonagh
        here's my updated code, i am a little more confident with this but I am getting a ) expected compiler error.

        anyone see anything please??
        I'm sure your compiler said some more: the line where it detected the syntax
        error and a bit more descriptive message than you've told us. Please don't make
        us guess but copy the error diagnostic message verbatim so that we can see
        what you saw.

        kind regards,

        Jos

        Comment

        • brendanmcdonagh
          New Member
          • Nov 2007
          • 153

          #5
          Sorry Jos

          Point def taken for future.

          I am using open university own compiler program.

          The { under the if statement is being highlighted and ) expected is all i'm beiing told.

          if
          {

          ^ that bracket

          Comment

          • JosAH
            Recognized Expert MVP
            • Mar 2007
            • 11453

            #6
            Originally posted by brendanmcdonagh
            Sorry Jos

            Point def taken for future.

            I am using open university own compiler program.

            The { under the if statement is being highlighted and ) expected is all i'm beiing told.

            if
            {

            ^ that bracket
            That must've been this line then:

            [code=java]
            if(whichPool.eq uals(this.getPo olName())
            [/code]

            Count your left and right parentheses. The compiler saw a { where it expected
            a last ), that's why it started to whine.

            kind regards,

            Jos

            Comment

            • brendanmcdonagh
              New Member
              • Nov 2007
              • 153

              #7
              And thats why this site is the best!

              Comment

              • brendanmcdonagh
                New Member
                • Nov 2007
                • 153

                #8
                Does anyone know why im getting a NULLPOINTEREXCE PTION line 3 pool A statistics at runtime with the follow code

                Code:
                /**
                 * Class Pool - represents a pool in the Rugby World Cup
                 * 
                 * @author (M255 Course Team) 
                 * @version (Version 1.0)
                 */
                
                import ou.*;
                import java.io.*;
                import java.util.*;
                
                public class Pool
                {
                   /* instance variables */
                   private String poolName; // the name of the pool
                   private Team[] teams;    // the teams in the pool
                   private final static int NOOFTEAMS = 5; // number of teams in each pool
                
                   /**
                    * Constructor for objects of class Pool
                    */
                   public Pool(String aName)
                   {
                      super();
                      this.poolName = aName;
                      this.teams = new Team[NOOFTEAMS];
                   }
                   
                
                   /**
                    * Returns the name of the receiver
                    */
                   public String getPoolName()
                   {
                      return this.poolName;
                   }
                   
                
                   /**
                    * Prompts the user for the name of the text file that 
                    * contains the results of the teams in this pool. The
                    * method uses this file to set the results of the teams.
                    */
                   public void loadTeams()
                   {
                       OUDialog.alert("Please Select a file containing results for : " + this.getPoolName());
                       String pathName = OUFileChooser.getFilename();
                       File aFile = new File(pathName);
                       BufferedReader bufferedFileReader = null;
                       try
                       {
                           Scanner lineScanner;
                           bufferedFileReader = new BufferedReader(new FileReader(aFile));
                           String whichPool = bufferedFileReader.readLine();
                           if(whichPool.equals(this.getPoolName()))
                           {
                               String currentLine = bufferedFileReader.readLine();
                               while(currentLine != null)
                               {
                                                            
                            lineScanner = new Scanner(currentLine);
                            lineScanner.useDelimiter(",");
                            Team aTeam =  new Team(lineScanner.next());
                            aTeam.setWon(lineScanner.nextInt());
                            aTeam.setDrawn(lineScanner.nextInt());
                            aTeam.setLost(lineScanner.nextInt());
                            aTeam.setFourOrMoreTries(lineScanner.nextInt());
                            aTeam.setSevenPointsOrLess(lineScanner.nextInt());
                            aTeam.setTotalPoints(aTeam.calculateTotalPoints());
                            currentLine = bufferedFileReader.readLine();
                            System.out.println("This is a test" + aTeam.calculateTotalPoints());
                        }
                    }
                }
                catch(Exception anException)
                {
                System.out.println("Error: " + anException);
                }
                finally
                {
                try
                {
                bufferedFileReader.close();
                }
                            
                catch(Exception anException)
                {
                System.out.println("Error: " + anException);
                }           
                 }
                
                }
                
                   /**
                    * Returns an array containing the names of the teams in
                    * this pool which will go on to the quarter-finals.
                    */
                   public String[] teamsToProgress()
                   {
                      /* to be completed by students */
                      return new String[2]; //Replace in solution
                   }
                   
                
                   /** 
                    * Prints the full results for each team in this pool 
                    * to the standard output.
                    */
                   public void displayPoolStats()
                   {
                      System.out.println("Statistics for "+ this.poolName);
                      for(int i = 0; i < NOOFTEAMS; i++)
                      {
                         System.out.println(teams[i].getName() + " " 
                                     + teams[i].getWon() + " "
                                     + teams[i].getDrawn() + " "
                                     + teams[i].getLost() + " "
                                     + teams[i].getFourOrMoreTries() + " "
                                     + teams[i].getSevenPointsOrLess() + " "
                                     + teams[i].getTotalPoints());
                     }                   
                
                   }
                }

                I am sending the following message

                Pool p = new Pool("Pool A");
                p.loadTeams();
                p.displayPoolSt ats();


                I have put a system.out.prin tln at end of while loop and everything seems fine

                Comment

                • blazedaces
                  Contributor
                  • May 2007
                  • 284

                  #9
                  Every time you catch anException, also write anException.pri ntStackTrace()

                  That will print out where the error is coming from. It will help to determine what exactly is the problem, because I'm sure it's not just line 3...

                  -blazed

                  Comment

                  • brendanmcdonagh
                    New Member
                    • Nov 2007
                    • 153

                    #10
                    Originally posted by blazedaces
                    Every time you catch anException, also write anException.pri ntStackTrace()

                    That will print out where the error is coming from. It will help to determine what exactly is the problem, because I'm sure it's not just line 3...

                    -blazed
                    Done that blazed,

                    Well kind of in stead of + anExcepton i just typed something so it wasn't an exception i had written.

                    I think it's got something to do with the last display method, I think i ve got to put all the data into an array. might get some sleep(when it's done!!)

                    Comment

                    • blazedaces
                      Contributor
                      • May 2007
                      • 284

                      #11
                      Originally posted by brendanmcdonagh
                      Done that blazed,

                      Well kind of in stead of + anExcepton i just typed something so it wasn't an exception i had written.

                      I think it's got something to do with the last display method, I think i ve got to put all the data into an array. might get some sleep(when it's done!!)
                      No, I mean instead of
                      Code:
                      catch(Exception anException)
                      {
                           System.out.println("Error: " + anException);
                      }
                      You should write
                      Code:
                      catch(Exception anException)
                      {
                           anException.printStackTrace();
                      }
                      Help us to help you.

                      -blazed

                      Comment

                      • JosAH
                        Recognized Expert MVP
                        • Mar 2007
                        • 11453

                        #12
                        Originally posted by brendanmcdonagh
                        Done that blazed,

                        Well kind of in stead of + anExcepton i just typed something so it wasn't an exception i had written.

                        I think it's got something to do with the last display method, I think i ve got to put all the data into an array. might get some sleep(when it's done!!)
                        Yep; in that while loop you create a Team all the time (aTeam) but you don't
                        do anything with it; somewhere else in your code you have a nice array of
                        Teams but you don't assign anything to its elements.

                        kind regards,

                        Jos

                        Comment

                        Working...