ArrayIndexOutOfBoundsException

Status
Not open for further replies.

Spatula

Ars Tribunus Angusticlavius
9,315
Subscriptor
I can't see why this would be out of bounds... I'm getting the error when trying to run the program (JBuilder6, JDK 1.3), at the point where I'm assigning a second dimension the the ragged arrays I've already assigned a first dimension to, and at a method call.

I'm allowed to get help troubleshooting (this is for a class), but not help with the program (make sense?) ie: if someone sees the reason why this is throwing this exception, I would love to know, but I'm not looking for a revision of my code that fixes it (which I know, is sometimes the easiest way to point out the problem).

Thanks!

Oh, and the arrows (<----------------) show where JBuilder says the exception is. They're not in the code.

code:<HR>
Code:
/**
 * Title: Text Manipulation, ELEC 278 and you
 * Description: Takes input file and outputs various statistics to an output file
 * Copyright: This code is released under free license. If you can find use for it,
        I'd be impressed (and surprised! and flattered! call me. Really. 555-1212. I'm lonely in this computer.
        My RAM ran off with the BIOS. She was kinda cute, too.)
 * @author Noel Atkins
 * @version 0.0.1 (512th BETA)
 */<P>import java.io.*;
import java.util.*;<P>public class Assignment1 {<P>  public static void Assignment1() {<P>  try {
    String FileName = "data.txt";<P>    //open the text file
    BufferedReader DataIn1 = new BufferedReader(new FileReader(FileName));<P>
    //now find the number of lines
    int numberOfLines = 0;
    String inputLine = DataIn1.readLine();
    while (inputLine != null) {
      inputLine = DataIn1.readLine();
      numberOfLines++;
      }
    DataIn1.close();<P>    //now make the arrays
    BufferedReader DataIn2 = new BufferedReader(new FileReader(FileName));
    String[][] a = new String[numberOfLines][];
    StringTokenizer line =  new StringTokenizer(DataIn2.readLine());<P>    for(int x=0; x<=numberOfLines; x++){
        int wordCounter = 0;
        while (line.hasMoreTokens()) {
          line.nextToken();
          wordCounter++;
          }
        a[x] = new String [wordCounter + 1]; <---------------------
      }
    DataIn2.close();<P>    //now fill them in
    BufferedReader DataIn3 = new BufferedReader(new FileReader(FileName));
    StringTokenizer lineForFilling = new StringTokenizer(DataIn3.readLine());
    int totalWords = 0;
    int totalNumberOfChars = 0;
    int b[] = new int[numberOfLines];
    for (int i=0; i<=numberOfLines; i++) {
      int position = 0;
      int wordsPerLine = 0;
        while (lineForFilling.hasMoreTokens()){
          a[i][position] = lineForFilling.nextToken();
          totalWords++;
          position++;
          wordsPerLine++;
          totalNumberOfChars = totalNumberOfChars + a[i][position].length();
          if (lineForFilling.hasMoreTokens() == false)
            b[i] = wordsPerLine;
          }
  }
DataIn3.close();<P>  //Now find out stats about the new array
    double averageWordsPerLine = (totalWords) / (numberOfLines);
    double averageCharsPerWord = (totalNumberOfChars-(totalWords-numberOfLines)) / (totalWords);<P>
  //output all the good things I've learned to the text file
  try
    {<P>      //open output file
      PrintWriter output = new PrintWriter(new FileOutputStream("out.txt")) ;
      //print out some lines
      for (int fish = 0; fish <=numberOfLines; fish++){
        output.print(b[fish]);
        int g = 0;
        for (int innerfish =0; innerfish<a[fish].length; innerfish++){
          output.print(" " + a[fish][innerfish]);
          }
      output.println();
      output.println("av. words per line = " + averageWordsPerLine);
      output.println("av. chars per word = " + averageCharsPerWord);<P>
      }
      output.close();
    }<P>    //some exceptions relating to file i/o
    catch( FileNotFoundException e )
    {
      System.out.println("file data.txt not found or could not be opened") ;
    }<P>    catch( IOException e )
    {
      System.out.println( "Error reading from file data.txt" );
    }<P>}
    //some exceptions relating to file i/o
    catch( FileNotFoundException e )
    {
      System.out.println("file data.txt not found or could not be opened") ;
    }
    catch( IOException e )
    {
      System.out.println( "Error reading from file data.txt" );
    }<P>}//close try
public static void main(String[] args){
  Assignment1();  <---------------------
  }<P>}//close Class
 

-Triple-

Ars Tribunus Angusticlavius
8,554
The problem, as you stated, is with these particular lines:

code:<HR>
Code:
String[][] a = new String[numberOfLines][];
code:<HR>
Code:
for(int x=0; x <= numberOfLines; x++){
code:<HR>
Code:
a[x] = new String [wordCounter + 1]; <---------------------

As you can see, the test (x <= numberOfLines) in the second line of code above means that in the final run of the loop, ((x == numberOfLines) == true). Note that you initialized the array of String a to be of width numberOfLines in the first line I listed above. Thus, during the final run of the loop, the third statement is equivalent to the following statement:

code:<HR>
Code:
a[numberOfLines] = new String [wordCounter + 1];

Since arrays are indexed from 0 to (size - 1), or in this case, 0 to (numberOfLines - 1), that will throw an ArrayIndexOutOfBoundsException.

Suggested fix? Change the test in the for() loop to (x < numberOfLines).
 
Status
Not open for further replies.