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):
- the values are larger than the array size- not possible because there are only 20 values.
- 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
print()look like? Please post the complete stack trace.4 rows, 5 columns, yet pass only one parametre toprintmethod as the value for both rows and columns. Of course it's gonna give an error..