Hello all, I am new to this forum. I think this will be an excellent place for learning things and I am looking forward to gaining more java knowledge.

My current predicament is the ArrayIndexOutOfBoundsException I am getting on a program I have written. I haven't been able to figure out why and am hoping someone could point me in the right direction. A warning: the following code probably will have a lot of java bad practice or there might be easier ways to do some things...if you are inclined constructive criticism on that will be appreciated but my main priority is figuring out how to get rid of the error.

I don't know how little or much of the code to include so I am going to show it all to you -

1. I created a WordReader class which has methods that will read various things from a textfile that will be given as a parameter to the method.

package thisPacket;

/*
* WordReader.java - A program to read words from a file
*/
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Array;

import java.util.*;

public class WordReader {
	
	String[][] transitions;

	public String[][] readTransitions(String fileName){
		BufferedReader br = null;
		String word;
		String[] rowOfTransition = new String [3];
		String[][] transArray = new String[5][3];		
		System.out.println("the transitions");
		try {
			br = new BufferedReader( new FileReader( fileName ) );
			br.readLine(); //skip line 1
			br.readLine(); //skip line 2
			br.readLine(); //skip line 3
			br.readLine(); //skip line 4
			//transitions begin from fifth line
			int index = 0;
		// loop and read a line from the file as long as we don't get null
			while( ( word = br.readLine() ) != null ){
				// add the read word to the wordList
				rowOfTransition = word.split(", ");
				transArray[index]=rowOfTransition;			
				System.out.println(index+" "+transArray[index][0]+" "+transArray[index][1]+" "+transArray[index][2]);
				index++;
			}
		} catch (IOException e) {
			e.printStackTrace();}
		finally {
			try {
				br.close();} 
			catch (IOException e) {
				e.printStackTrace();}
		}
		transitions = transArray;
		return transitions;
	} 
	


}

Here is an example of a valid input text file:
0, 1
q0, q1, q2
q0
q2
q0, 0, q0
q0, 0, q1
q0, 1, q0
q1, 0, none
q1, 1, q2

Now I know that the error is occuring on the readTransitions function on the following line:
transArray[index]=rowOfTransition;
Perhaps the problem is the way I have defined transArray as
String[][] transArray = new String[5][3];
? I know that the number of columns are always going to be 3 but the number of rows can be any number and since in my test file I knew there were only 5 lines to read I put five in there thinking I'll find a way of specifying number of rows later (read: I don't know how to read the number of lines left in the text file from the 5th line to the last line yet).

In case it is relevant here is the rest of my code that calls the readTransitions function

2. The NFAtoDFA class at the moment has a method called GetTransitions which wants to find out on a certain input state (always in first column) and certain input symbol (always in second column) what is the state that gets transitioned to.

package thisPacket;

import java.io.BufferedReader;
import java.util.Iterator;
import java.util.Set;
import java.util.Stack;

public class NFAtoDFA {
	
	WordReader wr = new WordReader();

	//! Returns all transitions from this state on specific input
	public String[] getTransition(String symbol, String inputState)
	{
		String[] transTo = null;
		int index=0;
		String[][] trans = wr.readTransitions("eg of a valid input nfa.txt");
		for (int i=0; i==trans.length; i++){
			if ((trans[i][0]==inputState)&&(trans[i][1] == symbol)) {
				transTo[index] =  trans[i][2];
				index++;
			}			
		}
		for (int i =0; i==transTo.length; i++)
			System.out.println("transTo");
			System.out.println(transTo);
		return transTo;
	}
	

}

And finally 3. Runnable class calls the getTransition method:

package thisPacket;

import java.io.BufferedReader;

public class Runnable {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		WordReader wr = new WordReader();
		NFAtoDFA n2d = new NFAtoDFA();		
		BufferedReader br;
		
		n2d.getTransition("0","q0");

	}

}

The error I get on running Runnable is:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at thisPacket.WordReader.readTransitions(WordReader.java:140)
at thisPacket.NFAtoDFA.getTransition(NFAtoDFA.java:38)
at thisPacket.Runnable.main(Runnable.java:15)

I have tried changing the transArray to [10][10] and whatever else and that doesn't work. I probably am not using 2-d arrays correctly. Any insight into how I can solve my problem would be very much appreciated. Thank you.

Well I can suggest you two not so good solutions :-
First is parse the contents of the file and check how many new line characters ("\n") do you find in the entire file and then you can set the first dimension of transArray accordingly.

Second is in the while loop on line no 33 for WordReader.java, there at run time you can detect when you have exceeded to size of the array and then create a new array of dimension [transarray.length+1][3] , transfer the contents of transArray to this new array, and finally assign this new array to transArray variable. So you now have a dynamically growing array, if the no of lines in your file exceed the initial capacity assigned to transArray.

Use an ArrayList, so your list can automatically grow as you need it to.

Use an ArrayList, so your list can automatically grow as you need it to.

Yep in front of that solution my post can be put in the wastebasket !!! ;)

Thanks for helping guys - ArrayLists worked like a charm. :)

could you please post the new code, in which you have implemented the ArrayList.
im not getting how to use it.

Not sure what trouble you are facing but here is an example of how I used array lists

ArrayList<String> alphabets = new ArrayList<String>();
try {
            br = new BufferedReader( new FileReader( fileName ) );
            String[] alphabetsArray;
            alphabetsArray = br.readLine().split(", ");
            for (int i = 0; i<alphabetsArray.length; i++){
                   alphabets.add(alphabetsArray[i]);
            }
			}
            } catch (IOException e) {} 
            finally {
	 try {
		//attempt to close file
		br.close();} 
	catch (IOException e) {
		//if an exception occurs print stack trace
		e.printStackTrace();}
	}

Does that make things clearer?

thanks for posting the code. but im yet not gettin it. i'll post a part of my code here.

public static int ROUTELENGTH[] = new int[23];    
    public static String[] START = new String[23];    
    public static String[] FINISH = new String[23];        
   
    public static String[] LINE = new String[3];

*
*
*
*
*

try {
            inREAD = new FileReader(inFILE);
            inBUFF = new BufferedReader(inREAD);
            String BUFF = new String();
            
            for(int lines=0; lines<24; lines++){
                BUFF = "";
                BUFF = inBUFF.readLine();
                
                LINE = BUFF.split(" "); 
                
                int TEMP = Integer.parseInt(LINE[0]);            
                ROUTELENGTH[lines] = TEMP;
                                
                START[lines] = LINE[1]; //the error is coming for this line: java.lang.ArrayIndexOutOfBoundsException: 1

                                
                System.out.println("the "+lines+" value is "+ROUTELENGTH[lines]+START[lines]);   
            }

the text file looks like
78 A D
67 H J

i need to read every line.
so i need to read the numbers and put them into the ROUTELENGTH array.
and read the 1st char, put them into START array.
and read the 2nd char, put them into FINISH array.

can you'll please help me out with this.
if any other part of the code is required, please let me know.
thank you.

I am by no means an expert and this is totally untested but would the following work:

ArrayList<int> routelength = new ArrayList<int>();

ArrayList<String> start = new ArrayList<String>();
ArrayList<String> finish = new ArrayList<String>();

try {
            br = new BufferedReader( new FileReader( fileName ) );
            String[] tempArray;
            tempArray = br.readLine().split(" ");
//now I think it has in array [78, A, D]

int TEMP = Integer.parseInt(LINE[0]); 
Routelength.add(TEMP);

Start.add(tempArray[1]);

}

Tell me does this work?

E.t.a: Also do a System.out.println(tempArray); after the split to see if stuff actually got stored in the array.

nah !
the same error is coming.

for adding the contents of the text file into the Sart array, the error is java.lang.ArrayIndexOutOfBoundsException: 1

What do you get when you go a System.out.println(tempArray); Does tempArray have the 3 things 78 A and D?

But like I said I am no expert - maybe you should create a thread and get the real experts to have a look at your code?

For reading lines from a file:

BufferedReader br=null;
try {
            br = new BufferedReader( new FileReader( fileName ) );
           String line = br.readLine();
           
            while (line!=null) {
                  //do something with line
                   //you read each line of the file, You don't know how many lines the file will have



                 //the last command of the while:
                 line = br.readLine();
            } 
           
} catch (IOException e) {
   System.out.println(e.getMessage());
} finally {
       try {
             br.close();
       } catch (Exception e) {
             System.out.println("Could not close file");
               e.printStackTrace();
       }
}

What do you want to do with each line read in the while loop?

After reading more carefully the rest of the thread I think you were trying to do this:
Read each line: <number> <String> <String>
If yes then combine this with the previous code:

ArrayList<Integer> routelength=new ArrayList<Integer>(); //I don't think you can store primitive types in the ArrayList
ArrayList<String> start=new ArrayList<String>();
ArrayList<String> finish=new ArrayList<String>();

//after reading the line within the while loop:
while(line!=null) {
  line=line.trim();

  String [] lineTokens = line.split(" ");

  if (lineTokens.length!=3) {
    System.out.println("Wrong line format");
  } else { 

     try {
        routelength.add(new Integer( lineTokens[0] ));
        start.add( lineTokens[1] )
        finish.add( lineTokens[2] );
     } catch (NumberFormatException nfe) {
        System.out.println("First token of line not a number");
     }

  } 

  line=br.readLine();
}

alright. i think im going to try out this set of code and will let you'll know if i get the desired output.
the problem is, i dont know much about ArrayList. never used it before.

can anyone tell me, why does the error occur: java.lang.ArrayIndexOutOfBoundsException: 1

and why is ArrayList the solution for it.

You don't know how many line the file will have so doing this is wrong:

inREAD = new FileReader(inFILE);
inBUFF = new BufferedReader(inREAD);
String BUFF = new String();
 
for(int lines=0; lines<24; lines++){
   BUFF = "";
   BUFF = inBUFF.readLine();
}

You assume that the file will have 24 lines but in general you will not know that. If the file has no more lines the inBUFF.readLine() will return null. And it will keep returning null for as long the loop runs. If you file has 3 lines the first 3 loop runs will give the values you want but the rest BUFF = inBUFF.readLine() will be null

So you use this:

String line = br.readLine(); //get the first line and check if it is null

while (line!=null) { if it is not null then the file has lines

//at the end you "read" the NEXT line and go at the beginning of the loop. If it is null means that there are no more lines and it does not enter the loop
line = br.readLine();
}

Since you don't know the exact size of the file you cannot use a fixed array:

public static String[] START = new String[23];

With the ArrayList you can add as many elements you want. If the file 1000 line the loop will run 1000 times and add to the ArrayList 1000 new items.
With the array you can only add 23 items, the size of the array.


As for the ArrayIndexOutOfBoundsException, the array: START = new String[23] has size 23, meaning that the index is 0 till 22
and the for loop:
for (int i=0 ; i<23 ; i++)

You use:
for (int i=0 ; i<24 ; i++)

What everybody does, and you should do the same is: NEVER use fixed numbers as upper limits in a for-loop. ALWAYS do this:

for (int i=0 ; i<START.length ; i++)

ok...so now i've tried the suggestions given to me.
but yet, the same error keeps coming.
maybe i might be yet doing something wrong. so im posting my code here.
you guys are the experts, please help me out eith it.

static ArrayList<Integer> ROUTELENGTH = new ArrayList<Integer>(); 
static ArrayList<String> START = new ArrayList<String>();
static ArrayList<String> FINISH = new ArrayList<String>();

*
*
*

try {
            inREAD = new FileReader(inFILE);
            inBUFF = new BufferedReader(inREAD);
            String BUFF = new String();
            
                BUFF = "";
                while(BUFF!=null){
                    BUFF = BUFF.trim();
                    BUFF = inBUFF.readLine();                
                    String[] LINE = BUFF.split(" "); 
                
                try{
                     ROUTELENGTH.add(new Integer (LINE[0]));
                     START.add(LINE[1]);
                     FINISH.add(LINE[2]);
                }catch (NumberFormatException nfe) {
                    System.out.println("First token of line not a number");
                }        

                System.out.println("the value is "+ROUTELENGTH+START);
                OUT.write("the value is "+ROUTELENGTH+START+"\n");
               }  //end of while          
            
}catch (Exception e) {
            System.out.println(e + "");
            OUT.write(e + "\n");
            System.exit(-1);
}

No you haven't tried what I have suggested. See the code for reading from the file, using BufferedReader and readLine()

commented: Incredibly patient! +4
import java.io.*;
class exampleif
{
public static void main(String args[])
{
int num=Integer.parseInt(args[0]);
if(num>1 & num <3)
{
if(num==1)
 {
   System.out.println("number equal to 1");
 }
if(num==2)
 {
  System.out.println("number equal to 2");
 }
if(num==3)
 {
 System.out.println("number equal to 3");
 }
}
else
System.out.println("there is no number between this");
}
}

i am getting error like

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0

read the post above yours.
it seems this has nothing to do with the original question, and the original thread has been dormant for several years.

if you want to ask us something:
* start a new thread
* explain what you try to do and what your code does
* show the relevant code in code blocks, so it will be readable
* provide all the information, including error messages (full stacktrace) and such.

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.