xImJugo
xImJugo

Reputation: 23

Java parsing command line arguments ( args[]) into an int[][] Type

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!

Upvotes: 2

Views: 2944

Answers (5)

Amit Kumar Lal
Amit Kumar Lal

Reputation: 5789

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

Upvotes: 1

PatrickChen
PatrickChen

Reputation: 1420

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

Upvotes: 0

Ashishkumar Singh
Ashishkumar Singh

Reputation: 3600

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(",");
        }
    }
}

Upvotes: 1

deHaar
deHaar

Reputation: 18568

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

Upvotes: 0

Bartosz Walusiak
Bartosz Walusiak

Reputation: 51

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.

Upvotes: 1

Related Questions