我正在编写一个简单的程序,将文本文件中的 20 个整数值输入到二维数组中。 我通过文本文件中的前两个值获取了行和列值。
据我了解,IndexOutOfBoundsException
意味着我的2D数组(4行5列):
- 值大于数组大小 - 不可能,因为 只有 20 个值。
- 没有足够的值来填充 数组-^原因
我错过了什么? 线程“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();
}
}
}
文本文件:(每行 1 个数字) 4 5 1 3 5 7 12 34 56 78 21 44 36 77 29 87 48 77 25 65 77 2
最佳答案
我敢打赌您没有将数据文件的名称传递给您的程序。
如果args.length == 0
则args[0]
抛出ArrayIndexOutOfBoundsException
这大约是您在该行上得到该错误的唯一方法。
关于Java-数组索引越界异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22029021/