繁体   English   中英

Java 字符串数组值到 2D int 数组

[英]Java String array values to 2D int array

我是初学者,我在 CSV 文件中有一个矩阵,如下所示:

0;1;1;0
1;0;1;1
1;1;0;0
0;1;0;0

我想将它导入一个 2D int 数组,这样我就可以用它做乘法并为我的图形程序计算一些东西。 到目前为止,这是我的代码:

try
    {
        BufferedReader br = new BufferedReader(new FileReader(path));
        String line = "";

        while ((line = br.readLine()) != null)
        {
            String[] values = line.replaceAll("\\D+","").split(";");

            for (int i = 0; i < values.length; i++)
            {
                for (int j = 0;j< values.length;j++)
                {
                    test[i][j] = Integer.parseInt(values[i]);
                    System.out.print(test[i][j]);
                }
                System.out.println();
            }
        }
        System.out.println("****");
    } catch (IOException e)
    {
        e.printStackTrace();
    }

我的问题是它会将第一行中的所有值放入矩阵的第一个 [] 中,而不是将每个值都放入每个 [] 中。 我尝试了不同的方法,但我总是得到相同的结果。 我恳请寻求帮助。

编辑:我没有正确澄清我的问题。 我的代码采用“0110”之类的第一个,并没有将每个值放入矩阵第一行的每个位置。 应该是test[0][0]的值为0,test[0][1]的值为1,test[0][2]的值为1,test[0][3]的值为0 . 其他线路也一样。 但它将整行放在 [0][0] 中,并且还切断了第一个数字。 所以它在那个地方没有 0110 而是 110。

您需要有一个可用于更改矩阵行的增量变量。 试试下面的代码:

try {
BufferedReader br = new BufferedReader(new FileReader(path));
String line = "";
int rowNumber = 0;
while ((line = br.readLine()) != null) {
    String[] values = line.split(";");
    for (int j = 0; j < values.length; j++) {
        test[rowNumber][j] = Integer.parseInt(values[j]);
        System.out.print(test[rowNumber][j]);
    }
    rowNumber++;
    System.out.println();
}
System.out.println("****");
} catch (IOException e) {
    e.printStackTrace();
}

使用 while 循环处理每一行。 使用一个变量(下面的i )来记住你所在的行。然后像你已经做的那样遍历分割线,但是使用正确的values索引( j ,而不是i ):

    BufferedReader br = new BufferedReader(new FileReader(path));
    String line = "";

    int i = 0; //to remember the line
    while ((line = br.readLine()) != null) {
        String[] values = line.split(";");
        for (int j = 0; j<values.length; j++) {
            test[i][j] = Integer.parseInt(values[j]); //use j here, not i!
            System.out.print(test[i][j]);
        }
        i++;
    }
  • 尝试仅使用“i”作为值的索引,因为不需要内部循环,您可以逐行读取 csv 中的值。
  • 删除该“replaceAll”方法,因为它可能会出错!

代码:

try {
    BufferedReader br = new BufferedReader(new FileReader(path));
    String line = "";
    int i = -1;    //here i will act as number of lines that have been "read"
    while ((line = br.readLine()) != null) {
        i+=1;    //incrementing i to increase line count, and move array to next iteration
        String[] values = line.split(";");    //removed replaceAll method
        for (int j = 0; j < values.length; j++) {
            test[i][j] = Integer.parseInt(values[j]);
            System.out.print(test[i][j]);
        }    //j for loop close
        System.out.println();
    }    //while close
    System.out.println("****");
} catch (IOException e) {
    e.printStackTrace();
}

您知道所需的矩阵大小。 嗯,这很方便,但如果你没有呢? 如果 CSV 文件中包含的矩阵数据恰好定期为动态大小,该怎么办。 您是否打算在每次要针对 CSV 文件运行应用程序时打开该文件并进行检查? 也许,也许你只是不必为目前的情况。 然而,很高兴知道您可以针对任何 CSV 文件中的任何大小的矩阵运行您的应用程序。

Java 中的二维数组仅仅是 Arrays 的数组。当声明数组时,它将具有固定大小,如果 CSV 文件中恰好包含大小不时变化的矩阵数据,这很好。 以下代码可以使用文件中包含的行数:

int numOfLines;
try {
    numOfLines = (int) java.nio.file.Files.lines(java.nio.file.Paths
            .get("MatrixData.csv"), java.nio.charset.Charset.defaultCharset()).count();
}
catch (java.io.IOException ex) {
    ex.printStackTrace();
}

当您读取数据行时,您将该行拆分为一个 String[] 数组,使用:

String[] values = line.replaceAll("\\D+","").split(";");

这并不好,因为在replaceAll()方法中以这种方式使用的\\D表达式将有效地从数据行字符串中删除所有非数字字符,并且这还将包括数据行用于分隔个人数字。 你的分裂不会做你真正想要的。 它只会为您提供一个 4 位数字字符串。 最好完全取消replaceAll()方法并执行类似以下操作:

String[] values = line.split("\\s*;\\s*");

传递给split()方法的表达式将处理分隔符前后的任意数量的空格(如果它们存在)。 如果有空格,它们将不会成为任何数组元素数据的一部分。

试试下面的代码。 它将处理 CSV 文件中的任何矩阵大小(即使列 [inner Arrays] 的长度不同):

String filePath = "MatrixData.csv";
// Get number of data lines in CSV file.
int lineCounter = 0;
try {
    lineCounter = (int) java.nio.file.Files.lines(java.nio.file.Paths
            .get(filePath), java.nio.charset.Charset.defaultCharset()).count();
}
catch (java.io.IOException ex) {
    ex.printStackTrace();
}
// ---------------------------------------
    
int[][] matrix = new int[lineCounter][]; //Declare & initialize the 2D Array
    
// 'Try With Resources' used here to auto-close the reader and free resources.
try (java.io.BufferedReader br = new java.io.BufferedReader(new java.io.FileReader(filePath))) {
    String line = "";
    lineCounter = 0;
    while ((line = br.readLine()) != null) {
        line = line.trim();
        if (line.isEmpty()) { continue; } // Skip blank lines (if any).
        /* Split the file lie into a String[] Array then convert 
           it to an int[] array (all in one line using Stream - Java8+).  */
        int[] intValues = java.util.stream.Stream.of(line.split("\\s*;\\s*"))
                .mapToInt(Integer::parseInt).toArray();
        // Copy the new int[] Array into the current row element of the 2D Array.
        matrix[lineCounter] = java.util.Arrays.copyOf(intValues, intValues.length);
        lineCounter++;
    }
} catch (java.io.FileNotFoundException ex) {
    ex.printStackTrace();
} catch (java.io.IOException ex) {
    ex.printStackTrace();
}
   
    
// Display the Matrix...
for (int[] ary : matrix) {
    String str = java.util.Arrays.toString(ary);
    System.out.println(str.substring(1, str.length() - 1));
}

暂无
暂无

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

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