0

I have the following code as Strings

[444398, 1]
[111099, 0]
[188386, 2]
[149743, 0]

and I want to make a two-dimensional array with each number as an int. For example,

int[][] temp = new int[4][2]

I am trying to use

String challengetemp = Arrays.toString(Challenge.challenge(players[0], players[1]));
challengeList[i][i] = Integer.parseInt(challengetemp.split("\\|",-1));

but for starters, ParseInt is getting a type mismatch and results in an error.

I would need to be able to access the info from the array afterwards as integers

3
  • 2
    parseInt(String) accepts a String as a parameter, not a String[], which is what the split(String, int) returns. Commented Jul 12, 2013 at 18:26
  • 2
    Why are you splitting on |? Can we see how your actual input look like? And what is Challenge? Please post an SSCCE Commented Jul 12, 2013 at 18:26
  • (I haven't checked these in code yet, but..) splitting on "[\\[\\]\n]" should split up your string on the first index, then splitting on "," should take care of the inner arrays. Commented Jul 12, 2013 at 18:30

2 Answers 2

2

And I would utilize StringTokenizer to do something like this.

    String str = "[444398, 1][111099, 0][188386, 2][149743, 0]";

        str = str.replace("[","");
        str = str.replace("]","|");

        int arr[][] = new int[4][2];
        StringTokenizer token = new StringTokenizer(str,"|");
        for(int i=0;i<4;i++)
        {
            StringTokenizer nextToken = new StringTokenizer(token.nextToken(),",");
         for(int j=0;j<2;j++)
          {
            String tokenValue = nextToken.nextToken();
            if(tokenValue.contains("|"))
            {
                tokenValue.replace("|", "");
            }
            arr[i][j]= Integer.parseInt(tokenValue.trim());
          }
        }

        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 2; j++) {
                System.out.println(arr[i][j]);
            }
        };

And you would have to modify a little to the loop, so that it would parse as many String to int array as you want.

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

Comments

1

I would do something like this:

    String string = "[444398, 1]";
    string = string.substring(1, string.length()-1); //Turns it into "444398, 1"
    String[] stringInArray = string.split(", "); // Then makes it ["444398", "1"]

    int[][] temp = new int[4][2];

    temp[0][0] = Integer.parseInt(stringInArray[0]);
    temp[0][1] = Integer.parseInt(stringInArray[1]);

You will have to modify it into a loop for doing multiple of course!

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.