2

Can somebody please tell me how to parse the following into an int[][] Type. This is the structure of numbers which are typed into the java args "1,2;0,3 3,4;3,4 " (the first 4 numbers should represent a matrix as well as the last 4 numbers; so i need both parsed as a int[][] ) but how can i take this and parse it into an int[][] type ?

First thing would be this i guess :

String[] firstmatrix = args[0].split(";");
String[] rowNumbers = new String[firstmatrix.length];
for(int i=0; i< firstmatrix.length; i++) {   
    rowNumbers = firstmatrix[i].split(",");

 }

but i cant get it to work out -.-

Edit : At first thank you for all your help. But i should have mentioned that exception handling is not necesarry. Also, i am only allowed to use java.lang and java.io

edit 2.0: Thank you all for your help!

4
  • 2
    For each of the arguments, get the rows by splitting on ";", and then for each of the rows get the numbers by splitting on ",". Basically you need a more deeply nested loop, something like (untested!) for (String arg: args) { for (String row: arg.split(";")) { for (String num: row.split(",")) /* do stuff */ }} Commented May 20, 2020 at 9:50
  • I am going to try this. Thank you Commented May 20, 2020 at 10:10
  • @xImJugo I have psoted an answer for the given input , u can drectly split it into array usin ",|;" regex Commented May 20, 2020 at 10:31
  • @xlmJugo check my updated answer. Commented May 21, 2020 at 6:01

5 Answers 5

1
public static void main(String[] args) throws IOException {
        List<Integer[][]> arrays = new ArrayList<Integer[][]>();

        //Considering the k=0 is the show, sum or divide argument
        for(int k=1; k< args.length; k++) {
            String[] values = args[k].split(";|,");
            int x = args[k].split(";").length;
            int y = args[k].split(";")[0].split(",").length;
            Integer[][] array = new Integer[x][y];
            int counter=0;
            for (int i=0; i<x; i++) {
                for (int j=0; j<y; j++) {
                    array[i][j] = Integer.parseInt(values[counter]);
                    counter++;
                }
            }
            //Arrays contains all the 2d array created
            arrays.add(array); 
        }
        //Example to Show the result i.e. arg[0] is show
        if(args[0].equalsIgnoreCase("show"))
            for (Integer[][] integers : arrays) {
                for (int i=0; i<integers.length; i++) {
                    for (int j=0; j<integers[0].length; j++) {
                        System.out.print(integers[i][j]+" ");
                    }
                    System.out.println();
                }
                System.out.println("******");
            }
    }

input

show 1,2;3,4 5,6;7,8

output

1 2 
3 4 
******
5 6 
7 8 

input for inpt with varible one 3*3 one 2*3 matrix

show 1,23,45;33,5,1;12,33,6 1,4,6;33,77,99

output

1 23 45 
33 5 1 
12 33 6 
******
1 4 6 
33 77 99 
******
Sign up to request clarification or add additional context in comments.

8 Comments

Why did you use scanner ? I guess this works the same with the java commando arguments ?
you have ... new int [2][2] but what if the input would be a 3x3 Matrix ? How could i change your fix numbers to a dynamic variable ?
@xImJugo I have updated with the variable , I thought the input is always going to be 2*2 , please check my updated answer.
@xImJugo also updated for command line arguments please check and let me know
I think i understand your code, but there i just one thing i dont get. How can i use the parsed int[][] ? I need them for my matrix class. Thats going to like this : MathMatrix mathmatrix1 = new MathMatrix(int[][] args[0]); MathMatrix mathmatrix2 = new MathMatrix(int [][] args[1]);
|
1

In the program arguments using a space splits it into two different arguments. What would probably be best for you is to change it to the format to:

1,2;0,3;3,4;3,4

Then

String[] firstMatrix = args[0].split(";");
System.out.print(Arrays.toString(firstMatrix));

Produces

[1,2, 0,3, 3,4, 3,4]

And doing

int[][] ints = new int[firstMatrix.length][2];
int[] intsInside;
for (int i = 0; i < firstMatrix.length; i++) {
    intsInside  = new int[2];
    intsInside[0] = Integer.parseInt(firstMatrix[i].split(",")[0]);
    intsInside[1] = Integer.parseInt(firstMatrix[i].split(",")[1]);
    ints[i] = intsInside;
}

System.out.print("\n" + Arrays.deepToString(ints));

Produces

[[1, 2], [0, 3], [3, 4], [3, 4]]

NOTE: Values 0, 1, and 2 in certain places in the code should be replaced with dynamic values based on array lengths etc.

1 Comment

I cant change the format to your example unfortunately. Nevertheless thank you.
1

As you have provided arguments like "1,2;0,3 3,4;3,4", it seems you will have args[0] and args[1] as two-parameter for input but you have only shown args[0] in your example. Below is a modified version of your code which might give you hint for your solution

public static void main(String[] args) {
    for (String tmpString : args) {
        String[] firstmatrix = tmpString.split(";");

  // Assuming that only two elements will be there splitter by `,`. 
        // If not the case, you have to add additional logic to dynamically get column length

    String[][] rowNumbers = new String[firstmatrix.length][2];
        for (int i = 0; i < firstmatrix.length; i++) {
            rowNumbers[i] = firstmatrix[i].split(",");
        }
    }
}

4 Comments

The input is basically 2 arguments, space separates the input into arg0 and arg1, please check once by executing via command line.
@Hades I did thats why I have a foreach loop on args
I am referring to the explanation u provided ""it seems you will have args[0] and args[1] as two-parameter for input but you have only shown args[0] in your example
@AshishkumarSingh yes its just 2 the arguments (args[0] and args[1])
0

You can try something like splitting the input by semicolon first in order to get the rows of the matrix and then split each row by comma in order to get the single values of a row.

The following example does exactly that:

public static void main(String[] args) {
    System.out.println("Please enter the matrix values");
    System.out.println("(values of a row delimited by comma, rows delimited by semicolon, example: 1,2;3,4 for a 2x2 matrix):\n");
    // fire up a scanner and read the next line
    try (Scanner sc = new Scanner(System.in)) {
        String line = sc.nextLine();
        // split the input by semicolon first in order to have the rows separated from each other
        String[] rows = line.split(";");
        // split the first row in order to get the amount of values for this row (and assume, the remaining rows have this size, too
        int columnCount = rows[0].split(",").length;
        // create the data structre for the result
        int[][] result = new int[rows.length][columnCount];
        // then go through all the rows
        for (int r = 0; r < rows.length; r++) {
            // split them by comma
            String[] columns = rows[r].split(",");
            // then iterate the column values,
            for (int c = 0; c < columns.length; c++) {
                // parse them to int, remove all whitespaces and put them into the result
                result[r][c] = Integer.parseInt(columns[c].trim());
            }
        }

        // then print the result using a separate static method
        print(result);
    }
}

The method that prints the matrix takes an int[][] as input and looks like this:

public static void print(int[][] arr) {
    for (int r = 0; r < arr.length; r++) {
        int[] row = arr[r];
        for (int v = 0; v < row.length; v++) {
            if (v < row.length - 1)
                System.out.print(row[v] + " | ");
            else
                System.out.print(row[v]);
        }
        System.out.println();
        if (r < arr.length - 1)
            System.out.println("—————————————");
    }
}

Executing this code and inputting the values 1,1,1,1;2,2,2,2;3,3,3,3;4,4,4,4 results in the output

1 | 1 | 1 | 1
—————————————
2 | 2 | 2 | 2
—————————————
3 | 3 | 3 | 3
—————————————
4 | 4 | 4 | 4

Comments

0

I tried the java8 stream way, with int[][] as result

String s = "1,2;0,3;3,4;3,4";
int[][] arr = Arrays.stream(s.split(";")).
       map(ss -> Stream.of(ss.split(","))
            .mapToInt(Integer::parseInt)
            .toArray())
       .toArray(int[][]::new);

With List<List<Integer>>, should be the same effect.

String s = "1,2;0,3;3,4;3,4";
        List<List<Integer>> arr = Arrays.stream(s.split(";")).
                map(ss -> Stream.of(ss.split(","))
                        .map(Integer::parseInt)
                        .collect(Collectors.toList()))
                .collect(Collectors.toList());
        System.out.println(arr);

Hope it helps

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.