Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Help with fixing a try catch problem
Index -> Programming, Java -> Java Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
Hugetanks




PostPosted: Wed Sep 18, 2019 5:53 pm   Post subject: Help with fixing a try catch problem

Write a program that reads from a file “input.txt” a list of numbers that are arranged into groups of various sizes. The program outputs the sum of the numbers in each group. Each group starts with a one-line descriptive phrase. The phrase can be anything that is not a number. Some groups may have zero number in them.

input.txt:
Group A
23
-12
29
-84
Group B
-2
-45
-90
123
26
19
-5
-30
9
Group C
Last Group
12
-34
23
47
52
8

Corresponding Output:
Group A
Sum = -44
Group B
Sum = 5
Group C
Sum = 0
Last Group
Sum = 108

My Code:
import java.util.*;
import java.io.*;

public class Exceptions2 {
public static void main(String[] args) {
try {
BufferedReader in = new BufferedReader(new FileReader("input.txt"));
boolean first = true;
String num;
int sum = 0;

while ((num = in.readLine()) != null) {
try {
sum += Integer.parseInt(num);
}
catch (NumberFormatException nfe) {
if (!first)
System.out.println("Sum = " + sum + "\n");
else
first = false;
System.out.println(num);
sum = 0;
}
}
System.out.println("Sum = " + sum);
in.close();
}
catch (IOException ioe) {
System.out.println("Problem accessing file!");
}
}
}

The problem is that I am using a nested try and catch within a try and catch. My teacher did say that we were able to not use nested try catch by declaring the BufferedReader out of the try catch and setting it to null and doing something else. Does anyone know how I would make it so that it is not a nested try catch?
Sponsor
Sponsor
Sponsor
sponsor
Display posts from previous:   
   Index -> Programming, Java -> Java Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 1 Posts ]
Jump to:   


Style:  
Search: