473,545 Members | 2,705 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

BufferedReader - Help!!!

153 New Member
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 3369
JosAH
11,448 Recognized Expert MVP
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 New Member
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 Recognized Expert MVP
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 New Member
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 Recognized Expert MVP
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 New Member
And thats why this site is the best!
Aug 11 '08 #7
brendanmcdonagh
153 New Member
Does anyone know why im getting a NULLPOINTEREXCE PTION 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.displayPoolSt ats();


I have put a system.out.prin tln at end of while loop and everything seems fine
Aug 11 '08 #8
blazedaces
284 Contributor
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
Aug 11 '08 #9
brendanmcdonagh
153 New Member
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!!)
Aug 11 '08 #10

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

Similar topics

4
15604
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 each other multiple lines (using PrintWriter.println()) at a time, and i don't know how many lines each of them will send. this wouldn't be a...
0
1135
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 my code that requires the user to input HTML code, which displays the token ID's: import java.io.*; public class Test { public static void...
3
2959
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: ----------------------------------------------------------------------------------------- org.apache.fop.apps.FOPException: Stream closed at java.io.CharArrayReader.ensureOpen(CharArrayReader.java:65) ...
3
2820
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
2275
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 like to delete one record in database, it always shows "record not found" in my program, even if the data has been deleted. I tried to used function...
5
3535
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 internet which helped me little bit. But there are lot of problems I am facing developing the whole game. I have drawn the Board and the two players can...
1
1642
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. public static int countLines(BufferedReader in) throws IOException ______________________________________________________________ 2) Implement...
4
16697
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 CsvTest.readFile(CsvTest.java:26) at Trial.main(Trial.java:24) I have no idea what to change here because I don't know what is wrong..please help me out... ...
0
1217
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 written in a format like this, "name,bday,sex,9-1,9-2,10-1,10-2.....,cumulative". my question is, should i read this whole line nd jz use the...
0
7499
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7432
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7689
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7943
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7786
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
3490
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3470
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1919
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1044
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.