473,406 Members | 2,439 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

BufferedReader - Help!!!

153 100+
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.

Expand|Select|Wrap|Line Numbers
  1.  /**
  2.     * Prompts the user for the name of the text file that 
  3.     * contains the results of the teams in this pool. The
  4.     * method uses this file to set the results of the teams.
  5.     */
  6.    public void loadTeams()
  7.    {
  8.        OUDialog.alert("Please Select a file containing results for : " + this.getPoolName());
  9.        String pathName = OUFileChooser.getFilename();
  10.        File aFile = new File(pathName);
  11.        BufferedReader bufferedFileReader = null;
  12.        try
  13.        {
  14.            Scanner lineScanner;
  15.            bufferedFileReader = new BufferedReader(new FileReader(aFile);
  16.            String currentLine = bufferedFileReader.readLine()
  17.            if (currentLine.equals(this.getPoolName());
  18.            {
  19.                currentLine = bufferedFileReader.newLine()
  20.    }  
  21.  
  22.  
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
Aug 11 '08 #1
11 3362
JosAH
11,448 Expert 8TB
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
Aug 11 '08 #2
brendanmcdonagh
153 100+
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?

Expand|Select|Wrap|Line Numbers
  1.  /**
  2.     * Prompts the user for the name of the text file that 
  3.     * contains the results of the teams in this pool. The
  4.     * method uses this file to set the results of the teams.
  5.     */
  6.    public void loadTeams()
  7.    {
  8.        OUDialog.alert("Please Select a file containing results for : " + this.getPoolName());
  9.        String pathName = OUFileChooser.getFilename();
  10.        File aFile = new File(pathName);
  11.        BufferedReader bufferedFileReader = null;
  12.        try
  13.        {
  14.            Scanner lineScanner;
  15.            bufferedFileReader = new BufferedReader(new FileReader(aFile));
  16.            String whichPool = bufferedFileReader.readLine();
  17.            if(whichPool.equals(this.getPoolName())
  18.            {
  19.                String currentLine = bufferedFileReader.readLine();
  20.                while(currentLine != null)
  21.                {
  22.  
  23.             lineScanner = new Scanner(currentLine);
  24.             lineScanner.useDelimiter(",");
  25.             Team aTeam =  new Team(lineScanner.next());
  26.             aTeam.setWon(lineScanner.next());
  27.             aTeam.setDrawn(lineScanner.next());
  28.             aTeam.setLost(lineScanner.next());
  29.             aTeam.setFourOrMoreTries(lineScanner.next());
  30.             aTeam.setSevenPointsOrLess(lineScanner.next());
  31.             aTeam.setTotalPoints(aTeam.calculateTotalPoints());
  32.             currentLine = bufferedFileReader.readLine();
  33.         }
  34.     }
  35. }
  36. catch(Exception anException)
  37. {
  38. System.out.println("Error: " + anException);
  39. }
  40. finally
  41. {
  42. try
  43. {
  44. bufferedFileReader.close();
  45. }
  46.  
  47. catch(Exception anException)
  48. {
  49. System.out.println("Error: " + anException);
  50. }           
  51.  }          
  52.  
  53.    }  
  54.  
Aug 11 '08 #3
JosAH
11,448 Expert 8TB
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
Aug 11 '08 #4
brendanmcdonagh
153 100+
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
Aug 11 '08 #5
JosAH
11,448 Expert 8TB
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:

Expand|Select|Wrap|Line Numbers
  1.            if(whichPool.equals(this.getPoolName())
  2.  
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
Aug 11 '08 #6
brendanmcdonagh
153 100+
And thats why this site is the best!
Aug 11 '08 #7
brendanmcdonagh
153 100+
Does anyone know why im getting a NULLPOINTEREXCEPTION line 3 pool A statistics at runtime with the follow code

Expand|Select|Wrap|Line Numbers
  1.  
  2. /**
  3.  * Class Pool - represents a pool in the Rugby World Cup
  4.  * 
  5.  * @author (M255 Course Team) 
  6.  * @version (Version 1.0)
  7.  */
  8.  
  9. import ou.*;
  10. import java.io.*;
  11. import java.util.*;
  12.  
  13. public class Pool
  14. {
  15.    /* instance variables */
  16.    private String poolName; // the name of the pool
  17.    private Team[] teams;    // the teams in the pool
  18.    private final static int NOOFTEAMS = 5; // number of teams in each pool
  19.  
  20.    /**
  21.     * Constructor for objects of class Pool
  22.     */
  23.    public Pool(String aName)
  24.    {
  25.       super();
  26.       this.poolName = aName;
  27.       this.teams = new Team[NOOFTEAMS];
  28.    }
  29.  
  30.  
  31.    /**
  32.     * Returns the name of the receiver
  33.     */
  34.    public String getPoolName()
  35.    {
  36.       return this.poolName;
  37.    }
  38.  
  39.  
  40.    /**
  41.     * Prompts the user for the name of the text file that 
  42.     * contains the results of the teams in this pool. The
  43.     * method uses this file to set the results of the teams.
  44.     */
  45.    public void loadTeams()
  46.    {
  47.        OUDialog.alert("Please Select a file containing results for : " + this.getPoolName());
  48.        String pathName = OUFileChooser.getFilename();
  49.        File aFile = new File(pathName);
  50.        BufferedReader bufferedFileReader = null;
  51.        try
  52.        {
  53.            Scanner lineScanner;
  54.            bufferedFileReader = new BufferedReader(new FileReader(aFile));
  55.            String whichPool = bufferedFileReader.readLine();
  56.            if(whichPool.equals(this.getPoolName()))
  57.            {
  58.                String currentLine = bufferedFileReader.readLine();
  59.                while(currentLine != null)
  60.                {
  61.  
  62.             lineScanner = new Scanner(currentLine);
  63.             lineScanner.useDelimiter(",");
  64.             Team aTeam =  new Team(lineScanner.next());
  65.             aTeam.setWon(lineScanner.nextInt());
  66.             aTeam.setDrawn(lineScanner.nextInt());
  67.             aTeam.setLost(lineScanner.nextInt());
  68.             aTeam.setFourOrMoreTries(lineScanner.nextInt());
  69.             aTeam.setSevenPointsOrLess(lineScanner.nextInt());
  70.             aTeam.setTotalPoints(aTeam.calculateTotalPoints());
  71.             currentLine = bufferedFileReader.readLine();
  72.             System.out.println("This is a test" + aTeam.calculateTotalPoints());
  73.         }
  74.     }
  75. }
  76. catch(Exception anException)
  77. {
  78. System.out.println("Error: " + anException);
  79. }
  80. finally
  81. {
  82. try
  83. {
  84. bufferedFileReader.close();
  85. }
  86.  
  87. catch(Exception anException)
  88. {
  89. System.out.println("Error: " + anException);
  90. }           
  91.  }
  92.  
  93. }
  94.  
  95.    /**
  96.     * Returns an array containing the names of the teams in
  97.     * this pool which will go on to the quarter-finals.
  98.     */
  99.    public String[] teamsToProgress()
  100.    {
  101.       /* to be completed by students */
  102.       return new String[2]; //Replace in solution
  103.    }
  104.  
  105.  
  106.    /** 
  107.     * Prints the full results for each team in this pool 
  108.     * to the standard output.
  109.     */
  110.    public void displayPoolStats()
  111.    {
  112.       System.out.println("Statistics for "+ this.poolName);
  113.       for(int i = 0; i < NOOFTEAMS; i++)
  114.       {
  115.          System.out.println(teams[i].getName() + " " 
  116.                      + teams[i].getWon() + " "
  117.                      + teams[i].getDrawn() + " "
  118.                      + teams[i].getLost() + " "
  119.                      + teams[i].getFourOrMoreTries() + " "
  120.                      + teams[i].getSevenPointsOrLess() + " "
  121.                      + teams[i].getTotalPoints());
  122.      }                   
  123.  
  124.    }
  125. }
  126.  
  127.  

I am sending the following message

Pool p = new Pool("Pool A");
p.loadTeams();
p.displayPoolStats();


I have put a system.out.println at end of while loop and everything seems fine
Aug 11 '08 #8
blazedaces
284 100+
Every time you catch anException, also write anException.printStackTrace()

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
Aug 11 '08 #9
brendanmcdonagh
153 100+
Every time you catch anException, also write anException.printStackTrace()

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!!)
Aug 11 '08 #10
blazedaces
284 100+
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
Expand|Select|Wrap|Line Numbers
  1. catch(Exception anException)
  2. {
  3.      System.out.println("Error: " + anException);
  4. }
  5.  
You should write
Expand|Select|Wrap|Line Numbers
  1. catch(Exception anException)
  2. {
  3.      anException.printStackTrace();
  4. }
  5.  
Help us to help you.

-blazed
Aug 11 '08 #11
JosAH
11,448 Expert 8TB
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
Aug 12 '08 #12

Sign in to post your reply or Sign up for a free account.

Similar topics

4
by: Dr.Kadzija | last post by:
i have a client-server application. client and server should communicate via tcp sockets. ok, so i use Sockets, PrintWriter and BufferedReader. the problem is that: both client and server will send...
0
by: NatMU1 | last post by:
I am coding a lexer that reads the input from a text file and displays the token ID's of each of the words in the file (e.g. if the file contains "<HEAD>" it displays the Symbol ID 10). Below is...
3
by: madumm | last post by:
Hi All; I was trying to get this "source" into a BufferedReader ; but when running it gives a Exception as follows:...
3
by: pankhudi | last post by:
I have written the code(in short) as below on the server side and client side import sun.audio.*; import java.io.*; import java.net.*; class Server2 {
6
crystal2005
by: crystal2005 | last post by:
Hello guys, I'm a beginner in Java application programming. I started to write a Java application in which link to MS Access database. I encountered a problem in deletion function. E.g. I would...
5
by: koonda | last post by:
Hi all, I am a student and I have a project due 20th of this month, I mean May 20, 2007 after 8 days. The project is about creating a Connect Four Game. I have found some code examples on the...
1
by: normbrc | last post by:
1) Implement (i.e., write the body of) the following method, countLines, that, given a BufferedReader parameter, counts and returns the number of lines of text in the corresponding file/stream. ...
4
by: HaifaCarina | last post by:
here's the complete lines of errors.. Exception in thread "main" java.util.NoSuchElementException at java.util.StringTokenizer.nextToken(StringTokenizer.java:332) at...
0
by: yjh0914 | last post by:
hi guys! so im basically editting my post i made earlier as it wznt as specific.. i have to make a program that basically ranks students by their cumulative gpa. the student's info is on a csv file...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.