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