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:

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]);
    }
}

Recommended Answers

All 13 Replies

try
{
<you code here>
}

catch (ArrayIndexOutOfBounds evt)
{
System.out.println(" Ur Message");
}

catch(NumberFormatException evt2)
{

System.out.println("Ur Message");
}

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:

try
			 {
          int[] letterCount = new int[26];
			 }
			 catch (ArrayIndexOutOfBoundsException e)
			 {
			 System.err.println("Caught ArrayIndexOutOfBoundsException: "+ e.getMessage());
			 e.printStackTrace();
			 }

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:

int[] letterCount = null;
try
			 {
          letterCount = new int[26];
			 }
			 catch (ArrayIndexOutOfBoundsException e)
			 {
			 System.err.println("Caught ArrayIndexOutOfBoundsException: "+ e.getMessage());
			 e.printStackTrace();
			 }

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 {
          int[] letterCount = new int[26];
/*
			 } catch (ArrayIndexOutOfBoundsException e) {
			 System.err.println("Caught ArrayIndexOutOfBoundsException: "+ e.getMessage());
			 e.printStackTrace();
			 }
*/

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:

void A() throws Exception {
}

void B() {
  try {
    A();
  } catch (Exception e) {
  }
}

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.

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:

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());
}

And something that I forgot:
NEVER, NEVER "hard code" the length of an array when you access it :

This:

for (i = 0; i < 26; i++)
              outfile.println((char)(i + 65) + " count = "
                             + letters[i]);

Should become this:

for (i = 0; i < letters.length ; i++)
              outfile.println((char)(i + 65) + " count = "
                             + letters[i]);

And this:

if (index >= 0 && index < 26)      //Step c
            letterC[index]++;

To this:

if (index >= 0 && index < letters.length)      //Step c
            letterC[index]++;

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:

Hi it's me again. Sorry for not checking what you wrote, I was only looking at the code you gave. It seems that I suggested not to use ArrayIndexOutOfBoundsException even though that is what you wanted.
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.:

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();
    }

When you add throws to a method (methodA) declaration, if an exception of that kind occurs in the method then it will not give you trouble inside the method. You will not have to put try-catch inside the method. But instead you throw it to the method that called methodA.
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:

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:

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

This assignment was given to me by my professor. I have tried implementing the changes you wrote about but now I have 35 errors

post you final code

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]);
    }
}

This:

FileReader inputStream = null;
			 PrintWriter outfile = null;
			 
			 try
			 {
			 
          FileReader inputStream = new FileReader("text.txt");
          PrintWriter outfile =
                  new PrintWriter(new FileWriter("textCh.out"));
..
..
}

Should be:

FileReader inputStream = null;
PrintWriter outfile = null;
			 try
			 {
          inputStream = new FileReader("text.txt");
          outfile = new PrintWriter(new FileWriter("textCh.out"));
..
..
}

The 3 methods writeTotal, chCount, copyText should be declared outside the main method. Meaning that you have a small problem with the parenthesis. You forgot to put one:
Add it there:


System.out.println(e.getMessage()) ;
}

} this one closes main

static void copyText(FileReader infile, PrintWriter outfile,


Also I don't know what the IntClass does? But try to fix the above first and see what happens. I think that it will work. Sometimes one misplaced '}' can give many errors

This assignment was given to me by my professor. I have tried implementing the changes you wrote about but now I have 35 errors

I think your professor simply wants you to catch what may potentially generate the indexOutOfBounds exception and handle it by making the number accessing the indice set to some value (for example, if the number is constantly incrementing, in the catch block set the number to zero, if decrementing set it to the array length - 1 ).

Either way, this is a poor way of doing it though it may please your unreasonable professor.

That worked. Thank you for all your help.
Here is the final code:

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
			 {
			 
          inputStream = new FileReader("text.txt");
          outfile = new PrintWriter(new FileWriter("textResults.out"));

          next.setNum(inputStream.read());

          while (next.getNum() != -1)
          {
              copyText(inputStream, outfile, next, letterCount);
              lineCount++;
              next.setNum(inputStream.read());
          } 

          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);
          index = (int) ch - 65;
          if (index >= 0 && index < 26)
            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]);
    }
}

I think your professor simply wants you to catch what may potentially generate the indexOutOfBounds exception and handle it by making the number accessing the indice set to some value (for example, if the number is constantly incrementing, in the catch block set the number to zero, if decrementing set it to the array length - 1 ).

Either way, this is a poor way of doing it though it may please your unreasonable professor.

That is no way to teach someone exceptions or proper java and I think that we both agree on that.
If you want to teach someone how to use exception, you use the NombarFormatException, not ArrayIndexOutOfBounds. What's the difference. One happens at runtime and cannot be avoided, so that is why you catch it and the other is not suppose to happen. If it happens then the code is wrong.

Suppose that you have a program that accepts 2 inputs and it must add them. The main has Strings as arguments: main (String [] args) . So since you don't what the user might enter you use the NombarFormatException.
But with ArrayIndexOutOfBounds you are supposed to check the index of the array. It will be the programmer's mistake to have such an exception thrown. I doubt that there is any case where using ArrayIndexOutOfBounds is better than doing something else. And NO ONE will ever write something like this:

try {
  for (int i=0;i<10;i++) {
    System.out.println(array[i]);
  }
} catch (ArrayIndexOutOfBounds e) {
  
}  

//or

try {
  for (int i=0; ;i++) {
    System.out.println(array[i]);
  }
} catch (ArrayIndexOutOfBounds e) {
  //exception thrown so array reading finished
}

When they can write this:

for (int i=0;i<array.length;i++) {
    System.out.println(array[i]);
  }

The very meaning of using exceptions is to prevent errors that are either unavoidable or unpredictable from happening

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.