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!

xImJugo
  • 23
  • 5
  • 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 */ }}` – neofelis May 20 '20 at 09:50
  • I am going to try this. Thank you – xImJugo May 20 '20 at 10:10
  • @xImJugo I have psoted an answer for the given input , u can drectly split it into array usin ",|;" regex – Amit Kumar Lal May 20 '20 at 10:31
  • @xlmJugo check my updated answer. – Amit Kumar Lal May 21 '20 at 06:01

5 Answers5

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
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 
******
Amit Kumar Lal
  • 5,537
  • 3
  • 19
  • 37
  • Why did you use scanner ? I guess this works the same with the java commando arguments ? – xImJugo May 20 '20 at 10:55
  • 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 May 20 '20 at 11:00
  • 1
    @xImJugo I have updated with the variable , I thought the input is always going to be 2*2 , please check my updated answer. – Amit Kumar Lal May 20 '20 at 12:03
  • 1
    @xImJugo also updated for command line arguments please check and let me know – Amit Kumar Lal May 20 '20 at 12:28
  • 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]); – xImJugo May 21 '20 at 10:06
  • And there is one more Problem i didnt think of -.- I need the the numbers as args[1] and args[2] because args[0] is going to be an method like "show", "multiply" or "add". So i guess i need to change the for each loop to a normal for loop and start counting from int i=1 ? – xImJugo May 21 '20 at 10:19
  • so i changed your for each loop to a for(int i=1; args.length; i+){ ... } and replaced your input varibale with args[i].split ... . When i try my "show" method everything works fine, but if i try add, i get an arrayOutofBounds Exception ? Do i have to change more of your code ? – xImJugo May 21 '20 at 10:50
  • @xImJugo changed the answer as per the requirement I have shown the example where the arg[0] is show hence printed the matrices .. u can implement for multiply and divide. – Amit Kumar Lal May 21 '20 at 10:52
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(",");
        }
    }
}
Ashishkumar Singh
  • 3,580
  • 1
  • 23
  • 41
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
deHaar
  • 17,687
  • 10
  • 38
  • 51
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

PatrickChen
  • 1,350
  • 1
  • 11
  • 19