简体   繁体   English

将String数组转换为2d数组

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

I have a String array like this 我有一个这样的字符串数组

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

how can i convert this to a 2d array 我如何将其转换为二维数组

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

3 is the size of 2d 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]);
        }
    }
}

Since arrays are 0-indexed in Java, you should change your loop initialization variable j to start at 0. 由于数组在Java中是0索引的,因此您应该将循环初始化变量j更改为从0开始。

Change: 更改:

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

to

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

Also, it seems you want a method to do the conversion, not a class so you should remove this from your method signature and put void since you aren't returning anything from the method. 另外,似乎您想要一个方法而不是一个class来进行转换,因此您应该从方法签名中删除此方法,并把它void因为您没有从该方法返回任何内容。

Change: 更改:

public static class convert(String[] lines)

To: 至:

public static void convert(String[] lines)

Also, you should use a different variable to iterate through the string array to make things more cleaner. 同样,您应该使用其他变量来遍历字符串数组,以使事情更清晰。 Since you are trying to use j , you can do that to. 由于您尝试使用j ,因此可以这样做。 Instead of initializing j to 1, you initialize it to 0 as I've said and use j+1 as the index for accessing the lines array. 无需将j初始化为1,而是将其初始化为0,然后将j+1用作访问lines数组的索引。

Here is how your code could look like: 您的代码如下所示:

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]);
        }
    }
}

Sin, 罪,

You have a couple of Off-by-one errors . 您有几个Off-by-one errors

Try this: 尝试这个:

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]);
                }
}

Please let me know if you have any questions! 请让我知道,如果你有任何问题!

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

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