繁体   English   中英

从.txt文件中的多行创建对象

[英]Create object from multiple lines in .txt file

我的问题:

我有具有该结构的txt文件:

20:00   Norwich Res-Milton K.   
2.45
3.30
2.45 
20:30   Everton Res-Blackpool   
2.24
3.25
2.73

我想要的是读取文本文件,并从内部数据创建对象。 我需要的一个对象是ie。(一个对象的字段):

    20:00   Norwich Res-Milton K. (String)
    2.45 (double)
    3.30 (double)
    2.45 (double)
...

我从txt读取数据的方法:

public ArrayList<Match> getMatches(){
    try{
        File file = new File("matches.txt");
        FileReader readerF = new FileReader(file);
        BufferedReader reader = new BufferedReader(readerF);

        String line = null;

        while((line = reader.readLine()) !=null){
               //here i dont know what to do 
        }
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(null, "");
    }
    return matches;
}

您有任何技巧/窍门吗? 非常感谢您的回答

编辑:

我的比赛课程:

    public class Match {

        private String matchName;
        private double course1;
        private double courseX;
        private double courseY;

        public Match(String matchName, double course1, double courseX, double courseY){
            this.matchName=matchName;
            this.course1=course1;
            this.courseX=courseX;
            this.courseY=courseY;

    }

}

提示: "//here i dont know what to do"的逻辑必须是这样的:

  1. 这是开始新比赛的线吗?
  2. 如是:
    1. 解析线以提取组件
    2. 创建新的比赛记录
    3. 使其成为当前比赛记录
  3. 如果不:
    1. 当前有比赛记录吗? 如果否,则为错误。
    2. 将行解析为数字
    3. 将新号码(无论其含义)添加到当前比赛记录中。

试试这个(我假设输入文件是有效的,所以您可能需要处理异常):

     public ArrayList<Match> getMatches(){
        try{
            File file = new File("matches.txt");
            FileReader readerF = new FileReader(file);
            BufferedReader reader = new BufferedReader(readerF);

            String line = null;
            String matchName = null;
            double course1;
            double courseX;
            double courseY;
            ArrayList<Match> matches = new ArrayList<>();
            int count = 0;

            while((line = reader.readLine()) !=null){
                   if (count%4 == 3) {
                       Match match = new Match(line, course1, courseX, courseY);
                       matches.add(match);
                   } else if (count%4 == 2) {
                       courseY = Double.parseDouble(line);
                   } else if (count%4 == 1) {
                       courseX = Double.parseDouble(line);
                   } else {
                       course1 = Double.parseDouble(line);
                   }
                   count++;
            }
        }
        catch(Exception e){
            JOptionPane.showMessageDialog(null, "");
        }
        return matches;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM