简体   繁体   English

从网格将数字导入2D数组Java

[英]Importing numbers from a grid into a 2D Array Java

So just a quick question here, I have done some work with file reading but not enough to be proficient with it. 因此,这里只是一个简单的问题,我已经完成了一些文件读取方面的工作,但还不够熟练。 I have a grid: 我有一个网格:

10 14 81 34 76

18 22 64 4  87

1  6  42 13 15

4  32 21 87 31

7  42 24 20 15

(just an example grid) (仅是示例网格)

I have it in a text file currently. 我目前在文本文件中。 How do I input each number into its own place on a 2D array, seems simple but with my limited knowledge I have been unable to do it! 我如何将每个数字输入到2D数组中的位置,这似乎很简单,但是由于我的知识有限,我无法做到这一点!

Assume first you know the size. 首先假设您知道尺寸。 first step is to do file reading. 第一步是读取文件。 create a bufferreader 创建一个bufferreader

BufferedReader br=new BufferedReader(new FileReader(path));

Then loop through this reader 然后遍历此阅读器

int[][] result=new int[rownum][columnnum];
int i =0;
While(br.ready()){
    String line=br.readline();
    String[] tokens=line.split(" ");
    // now put each in 2D array
   for(int j=0;j<tokens.length;j++){
        result[i][j]=Integer.parseInt(tokens[j]);
    }
    i ++;
}

If you don't know the size then in that loop you put in ArrayList. 如果您不知道大小,则在该循环中放入ArrayList。 Then use toArray method 然后使用toArray方法

Well , Its pretty logical . 好吧,这很合逻辑。

Let's breakdown your grid , 让我们细分您的网格,

  1. It is space delimited 用空格定界
  2. Consider each line to be a row of a 2D array. 将每一行视为2D阵列的一行。

Here's some code , 这是一些代码,

    File file = new File("test.txt");
    FileReader fileReader = new FileReader(file);
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    ArrayList<String> lines = new ArrayList<String>();
    String line;
    while ((line = bufferedReader.readLine()) != null) {
        lines.add(line);
    }
    fileReader.close();

Now the ArrayList lines has all your lines from the textfile. 现在,ArrayList行包含了文本文件中的所有行。 All you have to do now , is iterate throught it with a simple for loop and extract the values. 您现在要做的就是使用简单的for循环遍历它并提取值。

String [] singleline = lines.get(0).split(" "); // this array contains all integers at line 0 .

just parse it to an integer value and add it to your 2D array in any way you prefer . 只需将其解析为整数值,然后以您喜欢的任何方式将其添加到2D数组中即可。

 ArrayList<Integer> singleLineIntegers = new ArrayList<Integer>();
 for(i=0;i<temp.length;i++)
 singleLineIntegers.add(Integer.parseInt(temp[i]));

Now this singleLineIntegers array Contains all the integers in line 1 , use the lines array to repeat this and insert it into your 2d array. 现在,此singleLineIntegers数组包含第1行中的所有整数,使用lines数组重复此操作并将其插入到2d数组中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM