簡體   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