将二维数组值分配给变量

Assigning 2 dimensional array value to a variable

我正在读取一个文本文件并将每个逗号分隔的字符串存储在一个二维数组中。稍后我需要一种方法将每个单独的字符串分配给一个变量。

        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]));

打印

[A6]

我无法让它像这样打印每个值:

A6

这是文本文件:

A6,A7
F2,F3
F6,G6

你的数组设置有误。

你说你想要一个二维数组。二维数组如下所示。

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

但是你的数组是这样的。

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

从技术上讲,上面也是一个二维数组。但这几乎肯定不是你想要的。

如果是这样,那么给您带来麻烦的 3 行就是这些。

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

这个 for 循环不是必需的。只需用这个替换 for 循环即可。

         list.add(arr);

EDIT - 在阅读了其他评论后,我听说您的字面意思是每个内部数组中有 1 个元素.就像提到的其他评论一样,这没有多大意义,但如果那真的是你想要的,那么就使用你的旧程序,然后将 System.out.println(a[0][0]) 作为程序的最后一行之一来完成这个。