| | |
Exception Handling
Thread Solved |
•
•
Join Date: Jul 2008
Posts: 10
Reputation:
Solved Threads: 0
I have to create a program that reads the text, outputs the text as is and prints the number of lines and the number of times each letter appears in the text. I have to include an exception, so that if the array index goes out of bounds when the program accesses the array letterCount, it throws and handles the ArrayIndexOutOfBoundsException. I have the program completed and working , but I'm having trouble adding the exception to the program. Here is my code:
Java Syntax (Toggle Plain Text)
import java.io.*; public class CharacterCount { public static void main(String[] args) throws FileNotFoundException, IOException { int lineCount = 0; try { int[] letterCount = new int[26]; } catch (ArrayIndexOutOfBoundsException e) { System.err.println("Caught ArrayIndexOutOfBoundsException: "+ e.getMessage()); e.printStackTrace(); } IntClass next = new IntClass(); FileReader inputStream = new FileReader("text.txt"); PrintWriter outfile = new PrintWriter(new FileWriter("textCh.out")); next.setNum(inputStream.read()); while (next.getNum() != -1) { copyText(inputStream, outfile, next, letterCount); lineCount++; next.setNum(inputStream.read()); } //end while loop writeTotal(outfile, lineCount, letterCount); outfile.close(); } static void copyText(FileReader infile, PrintWriter outfile, IntClass next, int[] letterC) throws IOException { while (next.getNum() != (int)'\n') { outfile.print((char)(next.getNum())); chCount((char)(next.getNum()), letterC); next.setNum(infile.read()); } outfile.println(); } static void chCount(char ch, int[] letterC) { int index; int i; ch = Character.toUpperCase(ch); //Step a index = (int) ch - 65; //Step b if (index >= 0 && index < 26) //Step c letterC[index]++; } static void writeTotal(PrintWriter outfile, int lines, int[] letters) { int i; outfile.println(); outfile.println("The number of lines = " + lines); for (i = 0; i < 26; i++) outfile.println((char)(i + 65) + " count = " + letters[i]); } }
First of all, this:
int[] letterCount = new int[26] ;
does not throw an exception.
Second: Let me guess your program does not compile. This is why:
You declare letterCount inside the try { ... }. Meaning that outside try{...} no one can "see" it. So when you try to use it at the while loop you will get an error. If you have to give value to a variable inside the try{...} but you will have to use it outside as well then:
You declare letterCount outside try{} so anyone can see it.
By the way the above is not necessary, since the declaration does not throw an ArrayIndexOutOfBoundsException, unless you use negative value. And it is not very correct to catch such exceptions. It is up to the programmer to check in the code and make sure that you will never try to access an element of an array with an index greater than the length.
Try it without the try-catch.
As for you question, remove the throws Exception, from the main. You use these at method declarations in order to be caught by the method that calls the first method. No one calls main. Example:
int[] letterCount = new int[26] ;
does not throw an exception.
Second: Let me guess your program does not compile. This is why:
Java Syntax (Toggle Plain Text)
try { int[] letterCount = new int[26]; } catch (ArrayIndexOutOfBoundsException e) { System.err.println("Caught ArrayIndexOutOfBoundsException: "+ e.getMessage()); e.printStackTrace(); }
Java Syntax (Toggle Plain Text)
int[] letterCount = null; try { letterCount = new int[26]; } catch (ArrayIndexOutOfBoundsException e) { System.err.println("Caught ArrayIndexOutOfBoundsException: "+ e.getMessage()); e.printStackTrace(); }
By the way the above is not necessary, since the declaration does not throw an ArrayIndexOutOfBoundsException, unless you use negative value. And it is not very correct to catch such exceptions. It is up to the programmer to check in the code and make sure that you will never try to access an element of an array with an index greater than the length.
Java Syntax (Toggle Plain Text)
//try { int[] letterCount = new int[26]; /* } catch (ArrayIndexOutOfBoundsException e) { System.err.println("Caught ArrayIndexOutOfBoundsException: "+ e.getMessage()); e.printStackTrace(); } */
As for you question, remove the throws Exception, from the main. You use these at method declarations in order to be caught by the method that calls the first method. No one calls main. Example:
Java Syntax (Toggle Plain Text)
void A() throws Exception { } void B() { try { A(); } catch (Exception e) { } }
Check out my New Bike at my Public Profile at the "About Me" tab
Yes, including a throws on the end of main is considered bad programming practice since nothing can really catch an error generated from main and handle it afterward.
Only use throws on the end of main to save time when practicing something particular without bloating the code in try-catch blocks.
Use File I/O or Networking extensively for an example.
Only use throws on the end of main to save time when practicing something particular without bloating the code in try-catch blocks.
Use File I/O or Networking extensively for an example.
Last edited by Alex Edwards; Aug 11th, 2008 at 4:20 am.
Java Syntax (Toggle Plain Text)
IntClass next = new IntClass(); FileReader inputStream = new FileReader("text.txt"); PrintWriter outfile = new PrintWriter(new FileWriter("textCh.out")); next.setNum(inputStream.read()); while (next.getNum() != -1) { copyText(inputStream, outfile, next, letterCount); lineCount++; next.setNum(inputStream.read()); } //end while loop writeTotal(outfile, lineCount, letterCount); outfile.close();
The above code needs to be altered like this:
Java Syntax (Toggle Plain Text)
IntClass next = new IntClass(); FileReader inputStream = null; PrintWriter outfile = null; try { inputStream = new FileReader("text.txt"); outfile = new PrintWriter(new FileWriter("textCh.out")); next.setNum(inputStream.read()); while (next.getNum() != -1) { copyText(inputStream, outfile, next, letterCount); lineCount++; next.setNum(inputStream.read()); } //end while loop writeTotal(outfile, lineCount, letterCount); outfile.close(); } catch (Exception e) { System.out.println(e.getMessage()); }
Check out my New Bike at my Public Profile at the "About Me" tab
And something that I forgot:
NEVER, NEVER "hard code" the length of an array when you access it :
This:
Should become this:
And this:
To this:
NEVER, NEVER "hard code" the length of an array when you access it :
This:
Java Syntax (Toggle Plain Text)
for (i = 0; i < 26; i++) outfile.println((char)(i + 65) + " count = " + letters[i]);
Java Syntax (Toggle Plain Text)
for (i = 0; i < letters.length ; i++) outfile.println((char)(i + 65) + " count = " + letters[i]);
And this:
Java Syntax (Toggle Plain Text)
if (index >= 0 && index < 26) //Step c letterC[index]++;
To this:
Java Syntax (Toggle Plain Text)
if (index >= 0 && index < letters.length) //Step c letterC[index]++;
Check out my New Bike at my Public Profile at the "About Me" tab
•
•
•
•
I have to create a program that reads the text, outputs the text as is and prints the number of lines and the number of times each letter appears in the text. I have to include an exception, so that if the array index goes out of bounds when the program accesses the array letterCount, it throws and handles the ArrayIndexOutOfBoundsException. I have the program completed and working , but I'm having trouble adding the exception to the program. Here is my code:
Who told you to use this exception handling? Because what I suggested was generally correct: you don't want to catch such exception, but instead make sure it doesn't happen by checking the length of the array.
Anyway if you want ArrayIndexOutOfBoundsException here it is.:
Java Syntax (Toggle Plain Text)
static void chCount(char ch, int[] letterC) throws ArrayIndexOutOfBoundsException { int index; int i; ch = Character.toUpperCase(ch); //Step a index = (int) ch - 65; //Step b if (index >= 0 && index < 26) //Step c letterC[index]++; } static void writeTotal(PrintWriter outfile, int lines, int[] letters) throws ArrayIndexOutOfBoundsException { int i; outfile.println(); outfile.println("The number of lines = " + lines); for (i = 0; i < 26; i++) outfile.println((char)(i + 65) + " count = " + letters[i]); } static void copyText(FileReader infile, PrintWriter outfile, IntClass next, int[] letterC) throws IOException, ArrayIndexOutOfBoundsException { while (next.getNum() != (int)'\n') { outfile.print((char)(next.getNum())); chCount((char)(next.getNum()), letterC); next.setNum(infile.read()); } outfile.println(); }
The above method copyText has a throws because it calls chCount which throws an ArrayIndexOutOfBoundsException .
It depends where you want to handle it:
1st version:
Java Syntax (Toggle Plain Text)
void A(String s) { try { int i = Integer.parseInt(s); // do other stuff // perhaps return something if the method was not void } catch(NumberFormatException nfe) { //handle it here //print a message } } void B() { A("3"); A("a"); }
Or Version 2:
Java Syntax (Toggle Plain Text)
void A(String s) throws NumberFormatException { int i = Integer.parseInt(s); } void B() { try { A("3"); } catch (NumberFormatException nfe) { //handle it here } try { A("a"); } catch (NumberFormatException nfe) { //handle it here } }
So now that you have added the throws ArrayIndexOutOfBoundsException, go to where you call the methods and put them in a try-catch. Since in my suggestions I have already put your code in try-catch, simply add one more catch() { }
And please tell me who told you to use ArrayIndexOutOfBoundsException? And sorry for confusing you and for my many posts
Check out my New Bike at my Public Profile at the "About Me" tab
•
•
Join Date: Jul 2008
Posts: 10
Reputation:
Solved Threads: 0
Java Syntax (Toggle Plain Text)
import java.io.*; public class CharacterCount { public static void main(String[] args) throws FileNotFoundException, IOException { int lineCount = 0; int[] letterCount = new int[26]; IntClass next = new IntClass(); FileReader inputStream = null; PrintWriter outfile = null; try { FileReader inputStream = new FileReader("text.txt"); PrintWriter outfile = new PrintWriter(new FileWriter("textCh.out")); next.setNum(inputStream.read()); while (next.getNum() != -1) { copyText(inputStream, outfile, next, letterCount); lineCount++; next.setNum(inputStream.read()); } //end while loop writeTotal(outfile, lineCount, letterCount); outfile.close(); } catch (Exception e) { System.out.println(e.getMessage()); } static void copyText(FileReader infile, PrintWriter outfile, IntClass next, int[] letterC) throws IOException, ArrayIndexOutOfBoundsException { while (next.getNum() != (int)'\n') { outfile.print((char)(next.getNum())); chCount((char)(next.getNum()), letterC); next.setNum(infile.read()); } outfile.println(); } static void chCount(char ch, int[] letterC)throws ArrayIndexOutOfBoundsException { int index; int i; ch = Character.toUpperCase(ch); //Step a index = (int) ch - 65; //Step b if (index >= 0 && index < 26) //Step c letterC[index]++; } static void writeTotal(PrintWriter outfile, int lines, int[] letters) throws ArrayIndexOutOfBoundsException { int i; outfile.println(); outfile.println("The number of lines = " + lines); for (i = 0; i < 26; i++) outfile.println((char)(i + 65) + " count = " + letters[i]); } }
![]() |
Similar Threads
- purpose of exception handling 'finally' clause (Java)
- Arithmetic Exceptions and exception-handling statements (Java)
Other Threads in the Java Forum
- Previous Thread: Accessing JApplet "Window Close" [x] box
- Next Thread: Icons not showing?
| Thread Tools | Search this Thread |
911 actionlistener addressbook android api append applet application array arrays automation binary blackberry block bluetooth character chat class client code component consumer csv database desktop developmenthelp eclipse error fractal ftp game givemetehcodez graphics gui html ide image integer j2me j2seprojects japplet java javaarraylist javac javaee javaprojects jni jpanel julia lego linked linux list loops mac map method methods mobile netbeans newbie number objects online oriented panel printf problem program programming project projects properties recursion replaydirector reporting researchinmotion rotatetext rsa scanner se server set singleton sms sort sql string swing test textfields threads time title tree tutorial-sample ubuntu update windows working






