繁体   English   中英

将String数组转换为2d数组

[英]convert a String array to a 2d array

我有一个这样的字符串数组

3
1 5 5
2 -2 -3
15 -100 20

我如何将其转换为二维数组

1 5 5
2 -2 -3
15 -100 20

3是2d的大小

public static class convert(String[] lines){
    int n = Integer.parseInt(lines[0]);             
    int[][] matrix = new int[n][n];
    for (int j = 1; j < n; j++) {
        String[] currentLine = lines[j].split(" ");
        for (int i = 0; i < currentLine.length; i++) {
            matrix[j][i] = Integer.parseInt(currentLine[i]);
        }
    }
}

由于数组在Java中是0索引的,因此您应该将循环初始化变量j更改为从0开始。

更改:

for (int j = 1; j < n; j++) {

for (int j = 0; j < n; j++) {

另外,似乎您想要一个方法而不是一个class来进行转换,因此您应该从方法签名中删除此方法,并把它void因为您没有从该方法返回任何内容。

更改:

public static class convert(String[] lines)

至:

public static void convert(String[] lines)

同样,您应该使用其他变量来遍历字符串数组,以使事情更清晰。 由于您尝试使用j ,因此可以这样做。 无需将j初始化为1,而是将其初始化为0,然后将j+1用作访问lines数组的索引。

您的代码如下所示:

public static void convert(String[] lines)
    int n = Integer.parseInt(lines[0]);             
    int[][] matrix = new int[n][n];
    for (int j = 0, k = 1; j < n; j++) {
        String[] currentLine = lines[j + 1].split(" ");
        for (int i = 0; i < currentLine.length; i++) {
            matrix[j][i] = Integer.parseInt(currentLine[i]);
        }
    }
}

罪,

您有几个Off-by-one errors

尝试这个:

int n = Integer.parseInt(lines[0]); 
int[][] matrix = new int[n][n];
for (int j = 1; j <= n; j++) {
                String[] currentLine = lines[j].split(" ");
                for (int i = 0; i < currentLine.length; i++) {
                    matrix[j-1][i] = Integer.parseInt(currentLine[i]);
                }
}

请让我知道,如果你有任何问题!

暂无
暂无

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

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