我试图将已经找到的2D数组存储到1D数组中,以便以后进行更快的处理。但是,当我尝试填充1D数组时,我总是收到nullPointerException。发生的是一个txt文件,该文件具有我们首先读取的行数和列数,以获取进行2D数组处理的行数和列数。然后,每个索引将读取txt文件中的下一个数据元素,并将其存储在该索引中,直到所有50000个整数值都被存储为止。没问题。
现在,我想使用该2D数组并将所有元素存储到1D数组中,以便以后在不使用数组列表或将其排列顺序的情况下寻找答案时可以更快地进行处理,这很好,
int [][] data = null;
int[] arrayCount = null;
for (int row = 0; row < numberOfRows; row++)
{
for (int col = 0; col < numberOfCols; col++)
{
data[row][col] = inputFile.nextInt();
}
}
//Doesn't Work gives me excpetion
data[0][0] = arrayCount[0];
我在for循环中尝试了此方法,但是无论我得到什么NullPointerException
您尚未初始化data
和arrayCount
变量,请按照以下步骤对其进行初始化:
int[][] data = new int[numberOfRows][numberOfCols];
int[] arrayCount = new int[numberOfRows * numberOfCols];
在您的情况下,要将2D数组复制到1D数组,您可以使用以下方法:
numberOfRows = data.length;
if (numberOfRows > 0) {
numberOfCols = data[0].length;
} else {
numberOfCols = 0;
}
System.out.println("numberOfRows : "+numberOfRows);
System.out.println("numberOfCols : "+numberOfCols);
for (int row = 0, count = 0; row < numberOfRows; row++) {
for (int col = 0; col < numberOfCols; col++) {
arrayCount[count] = data[row][col];
count++;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句