Java:如何在1D数组中存储2D数组 [英] Java: How to store a 2D array within a 1D array

查看:78
本文介绍了Java:如何在1D数组中存储2D数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将已找到的2D数组存储到1D数组中,以便以后进行更快的处理.但是,当我尝试填充1D数组时,我总是收到nullPointerException.发生的是一个txt文件,该文件具有我们首先读取的行数和列数,以获取进行2D数组处理的行数和列数.然后,每个索引读取txt文件中的下一个数据元素,并将其存储在该索引中,直到所有50000个整数值都存储为止.没问题.

I trying to store my already found 2D array into a 1D array for faster processing later. However, I keep getting a nullPointerException when I try to fill the 1D array. What happens is a txt file has the number of rows and colums that we read first to get the row and column amount for doing the 2D array. Then each index reads the next data element on the txt file and stores it at that index until all 50 000 integer values are stored. That WORKS fine.

现在,我想采用该2D数组并将所有元素存储到1D数组中,以便以后在不使用数组列表或将其排列顺序的情况下寻找答案时可以更快地进行处理,

Now I want to take that 2D array and store all the elements into a 1D array for faster processing later when looking for answers without using an array list or put them in order, which is fine,

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是什么

I tried this in for loops but no matter what I get a NullPointerException

推荐答案

您尚未初始化dataarrayCount变量,请按照以下步骤对其进行初始化:

You haven't initialized the data and arrayCount variables, initialize it as follows :

int[][] data = new int[numberOfRows][numberOfCols];
int[] arrayCount = new int[numberOfRows * numberOfCols];

在您的情况下,要从2D复制到1D阵列,您可以使用以下方法:

In your case, to copy from 2D to 1D array you may use something like this :

    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++;
        }
    }

这篇关于Java:如何在1D数组中存储2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆