存储 ArrayList 数据并转换为 String[][]

发布于 2024-11-29 00:13:35 字数 997 浏览 0 评论 0原文

我认为我的代码在 ArrayList 中存储数据是正确的。但是,我无法将列表转换为 String[][]。这是我的代码:

        int row = 0;
        int col = 0;

        String fileInput = JOptionPane.showInputDialog(null, 
                "Please enter the path of the CSV file to read:");

        File file = new File(fileInput);

        BufferedReader bufRdr;
        bufRdr = new BufferedReader(new FileReader(file));
        String line = null;

        // Construct a new empty ArrayList for type String
        ArrayList<String[]> al = new ArrayList<String[]>();

        //read each line of text file
        while((line = bufRdr.readLine()) != null) {
            String[] columnData = line.split(",");
            al.add(columnData);
        }

        // Convert ArrayList to String array
        String[][] numbers = (String[][]) al.toArray(new String[al.size()][16]);

我收到一条错误,指出我无法转换为 String[][] 类型。关于我能做什么有什么想法吗?

编辑:所以转换问题解决了(编辑后的代码粘贴在上面) - 现在它什么也不输出。我觉得我一定是错误地存储了数据。我应该添加/更改什么?

I think I have the code correct for storing data in an ArrayList. However, I can't convert the list to a String[][]. Here's my code:

        int row = 0;
        int col = 0;

        String fileInput = JOptionPane.showInputDialog(null, 
                "Please enter the path of the CSV file to read:");

        File file = new File(fileInput);

        BufferedReader bufRdr;
        bufRdr = new BufferedReader(new FileReader(file));
        String line = null;

        // Construct a new empty ArrayList for type String
        ArrayList<String[]> al = new ArrayList<String[]>();

        //read each line of text file
        while((line = bufRdr.readLine()) != null) {
            String[] columnData = line.split(",");
            al.add(columnData);
        }

        // Convert ArrayList to String array
        String[][] numbers = (String[][]) al.toArray(new String[al.size()][16]);

I'm getting an error stating I can't convert to a String[][] type. Any ideas on what I can do?

EDIT: So the conversion problem is solved (the edited code is pasted above) - now its outputting nothing though. I feel like I must have stored the data incorrectly. What should I add/change?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

极致的悲 2024-12-06 00:13:35

该数组将是 String[]Object[],因此强制转换不起作用。您可以(并且应该)使用提供要填充的数组的 toArray() 版本:

String[][] numbers = (String[][]) al.toArray(new String[al.size()][]);

The array will be an Object[] of String[], so the cast doesn't work. You can (and should) use the toArray() version that supplies the array to populate:

String[][] numbers = (String[][]) al.toArray(new String[al.size()][]);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文