Assigning 2 dimensional array value to a variable

Viewed 45

I'm reading a text file and storing each comma separated string inside a 2 dimensional array. I need a way to assign each individual string to a variable later.

        try {
            Scanner scanner = new Scanner(new File(filePath));
            while (scanner.hasNextLine()) {
                String[] arr = scanner.nextLine().split(",");
                for (String item : arr) {
                    list.add(new String[] { item });
                }
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        String[][] ar = list.toArray(String[][]::new);
        System.out.println(Arrays.deepToString(ar[0]));

prints

[A6]

I can't get it to print each value like:

A6

This is the text file:

A6,A7
F2,F3
F6,G6
1 Answers

You have made your array incorrectly.

You said you want a 2 dimensional array. A 2 dimensional array looks like this.

[ <--- this line is the beginning of the outer array
    [A6, A7], <--- this line is the entirety of the first inner array
    [F2, F3], <--- this line is the entirety of the second inner array
    [F6, G6]  <--- this line is the entirety of the third inner array (no comma)
] <--- this line is the end of the outer array

But you made your array like this.

[
    [A6],
    [A7],
    [F2],
    [F3],
    [F4],
    [F6],
    [G6]
]

Technically speaking, the above is also a 2 dimensional array. But this is almost certainly not what you want.

And if that's the case, then the 3 lines that are causing you trouble are these.

         for (String item : arr) {
            list.add(new String[] { item });
         }

This for loop isn't necessary. Just replace that for loop with this.

         list.add(arr);

EDIT - After reading other comments, I am hearing the possibility that you literally meant to have 1 element inside of each inner array. Like the other comment mentioned, that doesn't make much sense, but if that's really what you want, then take your old program, and then just do System.out.println(a[0][0]) as one of the last lines in your program in order to accomplish this.

Related