• Post Reply Bookmark Topic Watch Topic
  • New Topic

Data reading/output from file  RSS feed

Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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!
Ranch Hand
Posts: 234
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
Something must be done about this. Let's start by reading this tiny ad:
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!