0

I have a board game define as

boardArray = new int[4][4];

and I have a string in this format:

String s = "[[0,0,2,0],[0,0,2,0],[0,0,0,0],[0,0,0,0]]"

Is there a way to put it in the int array? Consider that it should look like this

[0,0,2,0]
[0,0,2,0]
[0,0,0,0]
[0,0,0,0]
4
  • apply String[] chopped = s.substring(2,s.length()-2).split("\\],\\["); and then take it from there. You're responsible for turning the substrings into the right type, and putting them in the right places. Commented Oct 21, 2014 at 20:34
  • Yes there is a way. I would recommend using substring Commented Oct 21, 2014 at 20:35
  • 1
    I would recommend using Scanner with a preset delimiter. Commented Oct 21, 2014 at 20:36
  • Did you try json parser? Commented Oct 21, 2014 at 20:47

2 Answers 2

2

You could simply do the following:

String s = "[[0,0,2,0],[0,0,2,0],[0,0,0,0],[0,0,0,0]]";

String myNums[] = s.split("[^0-9]+");
//Split at every non-digit

int my_array[][] = new int[4][4];
for(int i = 0; i < 4; i++) {
    for(int j = 0; j < 4; j++) {
        my_array[i][j] = Integer.parseInt(myNums[i*4 + j + 1]);
        //The 1 accounts for the extra "" at the beginning.
    }
}

//Prints the result
for(int i = 0; i < 4; i++) {
    for(int j = 0; j < 4; j++)
        System.out.print(my_array[i][j]);
    System.out.println();
}
Sign up to request clarification or add additional context in comments.

2 Comments

or as a single loop for(int i=0; i<myNums.length(); i++) with my_array[i%4][i/4] = Integer.parseInt(myNums[i]);
.split... just what I thought about.
0

If you want to to it dynamically, I've written a librray: https://github.com/timaschew/MDAAJ The nice thing is, that it's really fast, because internally it's a one dimensional array, but provides you same access and much more nice features, checkout the wiki and and tests

MDDA<Integer> array = new MDDA<Integer>(4,4);

or initialize with an existing array, which is one dimensional "template", but will be converted into your dimensions:

Integer[] template = new Integer[] {0,0,2,0,  0,0,2,0,  0,0,0,0,  0,0,0,0};
MDDA<Integer> array = new MDDA<Integer>(template, false, 4,4);

//instead of array[1][2];
array.get(1,2); // 2

Comments

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.