将逗号和制表符的整数文本文件导入java数组

时间:2022-09-06 00:21:16

I have a text file that looks like the following:

我有一个文本文件,如下所示:

1    2,1    3,5    4
2    1,1    4,2    3,1
3    1,5    4,1    0
4    3,1    2,2    1,3

I want to separate the text file into two arrays so that the first array is only the numbers before the comma and the second array is only the numbers following the comma. The groups of numbers are separated by tabs. The output here should be:

我想将文本文件分成两个数组,以便第一个数组只是逗号前面的数字,第二个数组只是逗号后面的数字。数字组由制表符分隔。这里的输出应该是:

array1 = {{1,2,3,4},{2,1,4,3},{3,1,4,0},{4,3,2,1}};
array2 = {{0,1,5,0},{0,1,2,1},{0,5,1,0},{0,1,2,3}};

Thank you.

1 个解决方案

#1


1  

You can read each line individually and use a StringTokenizer to get the next pairs.

您可以单独读取每一行,并使用StringTokenizer来获取下一对。

First, count the number of lines in the input (n) and then the number of pairs in each line (m). Here, n = 4, m = 4.

首先,计算输入(n)中的行数,然后计算每行中的行数(m)。这里,n = 4,m = 4。

int[][] array1 = new int[n][m];
int[][] array2 = new int[n][m];

then, read in the input with StringTokenizer.

然后,使用StringTokenizer读入输入。

for (int i = 0; i < n; i++) {
    StringTokenizer line = new StringTokenizer(read line here);
    for (int j = 0; j < m; j++) {
        String next = line.nextToken(); //next pair
        String[] values = next.split(","); //split pair by comma
        array1[n][m] = Integer.parseInt(values[0]);
        if (values.length == 2) { //in case there is no comma
            array2[n][m] = Integer.parseInt(values[1]);
        }
    }
}

#1


1  

You can read each line individually and use a StringTokenizer to get the next pairs.

您可以单独读取每一行,并使用StringTokenizer来获取下一对。

First, count the number of lines in the input (n) and then the number of pairs in each line (m). Here, n = 4, m = 4.

首先,计算输入(n)中的行数,然后计算每行中的行数(m)。这里,n = 4,m = 4。

int[][] array1 = new int[n][m];
int[][] array2 = new int[n][m];

then, read in the input with StringTokenizer.

然后,使用StringTokenizer读入输入。

for (int i = 0; i < n; i++) {
    StringTokenizer line = new StringTokenizer(read line here);
    for (int j = 0; j < m; j++) {
        String next = line.nextToken(); //next pair
        String[] values = next.split(","); //split pair by comma
        array1[n][m] = Integer.parseInt(values[0]);
        if (values.length == 2) { //in case there is no comma
            array2[n][m] = Integer.parseInt(values[1]);
        }
    }
}