0

I'm making a simple program where I input 20 integer values from a text file into the 2D array. I obtained the row and column value through the first two values in the text file.

From what I understand, the IndexOutOfBoundsException means that my 2D array (4 rows and 5 columns):

  1. the values are larger than the array size- not possible because there are only 20 values.
  2. there are not enough values to fill the array- ^ reason

What am I missing? Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0

public class Practice {

public static void main(String[] args){
    int[][] thisArray=fillArray(args[0]);
    print(thisArray,thisArray.length);
}

public static int[][] fillArray(String myFile){
    TextFileInput in= new TextFileInput(myFile);
    String r=in.readLine();//4 rows
    String c=in.readLine();//5 columns
    int row=Integer.parseInt(r);//parse from string to int
    int col=Integer.parseInt(c);
    int[][] tempArray=new int[row][col];

    for(int fillRow=0; fillRow<row;fillRow++){
        for(int fillCol=0; fillCol<col;fillCol++){
            String temp= in.readLine();
            tempArray[fillRow][fillCol]=Integer.parseInt(temp);
        }
    }
    return tempArray;//return 2D array
}

public static void print(int[][] array,int length){
    for(int r=0;r<length;r++){
        for(int c=0;c<array[r].length;c++){
            System.out.print(array[r][c]);
        }
        System.out.println();
    }
}
}

textfile:(1 number per line) 4 5 1 3 5 7 12 34 56 78 21 44 36 77 29 87 48 77 25 65 77 2

5
  • can you write the text written in the file? Commented Feb 26, 2014 at 0:13
  • Where is the error occurring? What does method print() look like? Please post the complete stack trace. Commented Feb 26, 2014 at 0:14
  • what line is throwing IOOB? is there anything in args[0]? also how is r going to be an int if it is a whole line? Commented Feb 26, 2014 at 0:14
  • 1
    you must check the values of row and col before "int[][] tempArray=new int[row][col];" Commented Feb 26, 2014 at 0:14
  • Check your own comments. You write 4 rows, 5 columns, yet pass only one parametre to printmethod as the value for both rows and columns. Of course it's gonna give an error.. Commented Feb 26, 2014 at 0:18

3 Answers 3

2

I'd be willing to bet you're not passing the name of your data file to your program.

if args.length == 0 then args[0] throws ArrayIndexOutOfBoundsException

That's about the only way you can get that error on that line.

Sign up to request clarification or add additional context in comments.

4 Comments

so I'm using Eclipse and from what I've learned so far, you pass the name of your file just by making sure it is in the same directory. I have my txt file in the same src file. When I "run" it doesn't the text file fall into args[0]?
In eclipse click on run->debug configurations... When the dialog comes up, there should already be an entry for Practice (since you ran it already). Select it then click the arguments tab. Add your data file name to the "Program Arguments" box.
yup. I didn't pass my name of data file into my program. Thanks!
You should check the line number on the exception stack trace. That way you can see exactly what line of code is causing the error.
1

Your code looks fine, but I think you have to check the values of row and col before

int[][] tempArray=new int[row][col];

Most probably, that's where the error is.

UPDATE - bingo. it's

fillArray(args[0])

you're not passing any parameter to your program.

try instead

fillArray("c:\\path\\to\\my\\file.txt");

3 Comments

what do you mean by checking the values of row and col? because aren't I initializing the tempArray with the row and col? Why would I need to check something I am initializing?
I mean adding System.out.println("cols = "+col);System.out.println("rows = "+row);
yup. I thought I was passing my file into args[0] but I wasn't. When put the path in it works. Thanks
0

I'd do it more like this:

package cruft;

import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;

/**
 * ArrayDemo
 * @author Michael
 * @link http://stackoverflow.com/questions/22029021/java-array-index-out-of-bounds-exception
 * @since 2/25/14 7:18 PM
 */
public class ArrayDemo {
    public static void main(String[] args) {
        Reader reader = null;
        try {
            if (args.length > 0) {
                reader = new FileReader(args[0]);
                int[][] thisArray = fillArray(reader);
                for (int i = 0; i < thisArray.length; ++i) {
                    for (int j = 0; j < thisArray[0].length; ++j) {
                        System.out.println(String.format("[%5d, %5d]: %5d", i, j, thisArray[i][j]));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(reader);
        }
    }

    private static void close(Reader reader) {
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static int[][] fillArray(Reader reader) throws IOException {
        int [][] array;
        BufferedReader br = new BufferedReader(reader);
        String line;
        int maxRows = Integer.parseInt(br.readLine());
        int maxCols = Integer.parseInt(br.readLine());
        array = new int[maxRows][maxCols];
        int i = 0;
        int j = 0;
        while ((line = br.readLine()) != null) {
            if (StringUtils.isNotBlank(line) && !line.startsWith("#")) {
                array[i][j++] = Integer.parseInt(line);
                if (j == maxCols) {
                    ++i;
                    j = 0;
                }
            }
        }
        return array;
    }
}

Here's the input file I used: first value is # rows, second is # cols, the rest are the matrix values.

2
3

# first row
1
2
3

# second row
4
5
6

Here's the output I got with a simple file, one value per line. I read in a 2x3 matrix:

[    0,     0]:     1
[    0,     1]:     2
[    0,     2]:     3
[    1,     0]:     4
[    1,     1]:     5
[    1,     2]:     6

Process finished with exit code 0

4 Comments

That would still have the same error at args[0] since args.length is 0
No, you don't seem to understand - I compiled and ran this code and got the output I posted. My code is quite correct. I check for no command line args. Mine runs if there are no command line args; just does nothing.
I see. Although I don't think the OPs intention was to have no output. :)
Exactly; if you give it a command line argument that points to the file you want to read you'll get output, like I posted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.