1

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
  • 2
    why are you using a 2D array if the inner array is just one element each? Do you want each input line as one row in the 2D array (list.add(arr), no for loop)? Anyway to access the element inside an array inside another array (a 2D array): a[0][0] (that is System.out.println(a[0][0]);) Commented May 28, 2022 at 19:45

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

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.