1

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

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]);
        }
    }
}
2
  • Fix the typo j = 1 ---> j = 0, other than that it's all good. Commented Oct 27, 2014 at 3:03
  • 1
    @dasblinkenlight, he would actually have to then change "lines[j].split(" ");" line to "String[] currentLine = lines[j+1].split(" ");" which would be two changes, or he could just leave j alone and change the matrix assignment, please see my answer for more detail! Commented Oct 27, 2014 at 3:26

2 Answers 2

1

Sin,

You have a couple of 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!

Sign up to request clarification or add additional context in comments.

Comments

1

Since arrays are 0-indexed in Java, you should change your loop initialization variable j to start at 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.

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. 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.

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

1 Comment

thanks so much. it worked. the problem is "String[] currentLine = lines[j + 1].split(" ");"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.