【发布时间】:2014-03-13 05:53:56
【问题描述】:
我不断收到这个java.lang.ArrayIndexOutOfBoundsException: 5 错误,不知道为什么。我正在尝试将数字从文本文件存储到我的二维数组中,但它没有正确存储数据。此外,当我将数据存储到二维数组中时,我也不允许使用任何预定义的 java 方法,例如“.length”实例字段。基本上我有一个与驱动程序文件交互的类文件。
这是名为“numbers”的文本文件:
3 5 8 2 4 1 7 9 11 14
这是包含方法的类文件:
public class array_class2D//class header
{
//private instance variables
final private int rows = 4;
final private int columns = 5;
public final int maxsize = 20;
int r = 0;
int c = 0;
private int position_r = 1;
private int position_c = 2;
int[][] c_array = new int[rows][columns];
public void arrayPrint2D()
{
System.out.println("Printing out the Complete array: ");
for(int r = 0; r < rows; r++)
{
for(int c = 0; c < columns; c++)
{
//if( count2 < count || c_array[r][c] != 0 )
//{
System.out.print(c_array[r][c] + " ");
// count2++;
//}
}
System.out.println();
}
}
public void store2D(int num)
{
System.out.println("R: " + r);
System.out.println("C: " + c);
c_array[r][c] = num;
if(r == 0 && c < columns)
{
c++;
}
else if(r == 0 && c == columns)
{
r++;
c = 0;
}
else if(r == 1 && c < columns)
{
c++;
}
else if(r == 1 && c == columns)
{
r++;
c = 0;
}
else if(r == 2 && c < columns)
{
c++;
}
else if(r == 2 && c == columns)
{
r++;
c = 0;
}
else if(r == 3 && c < columns)
{
c++;
}
else if(r == 3 && c == columns)
{
r++;
c = 0;
}
else if(r == 4 && c < columns)
{
c++;
}
else
{
System.out.println(" Its Done. ");
}
}
}
这是我的驱动程序文件:
import java.io.*;
import java.util.Scanner;
public class array2D_Driver
{
public static void main(String[] args) throws IOException
{
//Intance variables
int num = 0;//used to store elements from txt file
int input;//used to store user input
int number = 0;//used in while loop below to test user input
//object to use methods
array_class2D object = new array_class2D();
//Scanner object to read keyboard input
Scanner keyboard = new Scanner(System.in);
//Opens the file
File file = new File("numbers.txt");
Scanner inputFile = new Scanner(file);
System.out.println("***************Array Manipulation Program****************");
System.out.println("\n\n");
//Calling print method to show arrat is empty
object.arrayPrint2D();
System.out.println();//Buffer line
//Reads the file elements into the array
while (inputFile.hasNext())
{
num = inputFile.nextInt();//Basically each line on the text file has one element that is stored into the 'num' variable.
object.store2D(num);//The num variable is then passed as a integer through the store method's parameters
}
object.arrayPrint2D();
}
}//End of main method
提前谢谢你!
【问题讨论】:
标签: java arrays multidimensional-array indexoutofboundsexception