The following program reads input from a .txt file and prints out the text all in lowercase and then prints out the frequency of the letters used. The problem that I am having is I can get my "try" block to work when the "for loop" is not there and same with the "for loop"...works when I remove the "try" block ? Program does what I want it to do , I just can not get the everything to work as one ? Thank you for any suggestions in advance.
You need the instantiation of the FileReader and the BufferedReader inside a try. You also need to close the Reader; leaving a Reader open may cause a resource leak because the file may be unaccessible to other applications.You need the finally to make sure the BufferedReader is closed regardless, whether an Exception is thrown or not.
You need the finally inside a try bcause the close() method declares it might throw an Exception
You need the BufferedReader declaration before the inner try so it is still in scope for the finally block.
You need the bit that reads the text from the file inside the inner try; you don't need the code to count the letters, because that won't throw an Exception.
By using this intensive Exception handling, you can be sure all checked Exceptions are handled and you can remove the throws declaration.
Your application appears to be counting and printing the letters correctly, but only for the first line in the input. You will have to work out how to add successive lines to your counting.
Why are you creating the letters char array? You don't appear to be using it.
Joined: Oct 23, 2006
Ok, I have reworked the code. Problem I am having is that I can not find enough info anywhere on nested "try" blocks. So again when I run each loop on it own everything works. When I try to nest them in a try block , I will get the second loop to kind of work but never the first. Can anyone see the issue that i am having and provide me with some insight to my incorrect nesting of the try block. Thank you.
Joined: Oct 13, 2005
Somebody else has a problem with slight similarity to yours; it might be worth looking at this thread. I made a mistake in the code I posted yesterday. Sorry. It saysThat should readOtherwise if there is an exception in the try block, the br will be null at this point and you will suffer a NullPointerException.
You have a problem with your letters array. You don't actually need it, and you don't need to read into it because you can create a char array directly from a String. In fact you did in earlier versions of the code. If you try to read a String <250 characters long into it, you overrun the end of the String and suffer a StringIndexOutOfBoundsException.
Joined: Oct 13, 2005
And don't write "IOException" in the catch (Exception) block. It makes for confusing error messages.