从.txt读入2D数组 [英] Reading from a .txt into a 2D array

查看:60
本文介绍了从.txt读入2D数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,如果我的代码看起来很糟糕,我的编程经验还不丰富。我需要从.txt传输以下格式的文本:日期名称地址等。

Sorry if my code seems bad, I'm not that experienced at programming. I need to transfer text from a .txt in the format of: Date-Name-Address-etc..

我正在读取文件,然后拆分字符串与String.split(-)。我在循环时遇到麻烦。

I'm reading in the file, then splitting the string with String.split("-"). I'm having trouble with the loops.

    try{
        File file = new File("testwrite.txt");
        Scanner scan = new Scanner(file);
        String[] test = scan.nextLine().split("-");
        while(r<100){
            while(c<6){
                data[r][c] = test[c];
                test = scan.nextLine().split("-");
                c++;
            }
            r++;
            c = 0 ;
        }
        System.out.println(data[1][5]);
    }catch(Exception e){
        System.out.println("Error: " + e.getMessage());
    }


推荐答案

二维数组只是数组,因此您可以直接使用 split 结果存储一行数据。

Two dimensional array is just "array of arrays", so you can directly use split result to store the data of one line.

            File file = new File("testwrite.txt");
            Scanner scanner = new Scanner(file);
            final int maxLines = 100;
            String[][] resultArray = new String[maxLines][];
            int linesCounter = 0;
            while (scanner.hasNextLine() && linesCounter < maxLines) {
                resultArray[linesCounter] = scanner.nextLine().split("-");
                linesCounter++;
            }

这篇关于从.txt读入2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆