Meaningless Drivel is fun!
The moose likes Beginning Java and the fly likes Data reading/output from file Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Data reading/output from file" Watch "Data reading/output from file" New topic

Data reading/output from file

Amil Mehmedagic

Joined: Feb 27, 2004
Posts: 22

I have a set of data, such as this:
Anne Other 15 19 15 12 18
Roger the Dodger 11 13 9 15
Eric the Red 19 19 20 15 20
Java Janet 20 20 20
What I need to do is to create another file and print the sum of this data, so it looks like this:
Anne Other 79
Roger the Dodger 48
Eric the Red 93
Java Janet 60
My window however shows the following output:
How do I get Java to print out the names from the other file? Do I need to store all of the data in an array?
Here is my code:
public class ProcessingMarks {

public static void main (String [] args) throws IOException {
/*BufferedReader br =
new BufferedReader(new FileReader("marks.txt"));
FileWriter fw = new FileWriter(fileName, true);
PrintWriter pw = new PrintWriter(fw);*/
FileReader fr = new FileReader("marks.txt");
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("results.txt");
PrintWriter pw = new PrintWriter(fw);

String line = br.readLine();

int sum;
while (line != null) {
StringTokenizer st = new StringTokenizer(line);
sum = 0;
while (st.hasMoreTokens()) {
try {
//sum = sum + Integer.valueOf(st.nextToken());
//sum = sum + Integer.valueOf(st.nextToken()).intValue();
sum = sum + Integer.parseInt(st.nextToken());
} catch (NumberFormatException e) {}
line = br.readLine();



Looking forward to your response!
bart zagers
Ranch Hand

Joined: Feb 05, 2003
Posts: 234
You only use the tokens that are numbers and ignore the thrown exceptions for the rest of the tokens. It might be better to check first if the token is a number or not, something like this:

[ May 27, 2004: Message edited by: Bart Sawyer ]
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Ah, I wondered how you'd skip over name to get the numbers. You didn't really skip, you just caught the number exceptions when the tokens were part of the name. Since those are exactly the bits of information that are missing from your output, think about what could go in the catch clause to show those tokens to the user. Maybe print them as you find them? Maybe build up a name string and print it later?

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
I agree. Here's the link:
subject: Data reading/output from file
It's not a secret anymore!