Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create 2d array in java with scanner input

I want to create 2D array in java with given scanner input.

1 3
2
3
-1

and the result will be like that [[1,2],[3],[3],[-1]].

I tried with following one unfortunately, it was still not correct. Please let me know how to do it, thanks.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    Scanner sc = new Scanner(System.in);
    int nodes[][] = new int[4][2];
    for(int i = 0; i < 4; i++) {
        for(int j = 0; j < 2; j++) {
            nodes[i][j] = sc.nextInt();
        }
    }

>Solution :

Read an entire line. Then split the line on space. The size of the array is the number of items. Create the sub-array using that length:

int nodes[][] = new int[4][];
for(int i = 0; i < 4; i++) {
    String[] s = sc.nextLine().split(" ");
    nodes[i] = new int[s.length];
    for(int j = 0; j < s.length; j++) {
        nodes[i][j] = Integer.parseInt(s[j]);
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading