在while循环中有一个for循环来从文件中专门读取?

时间:2015-04-25 20:14:38

标签: java file-io

我有一个包含多个团队的文本文件。所有团队都有不同的变量但价值不同。但是到最后,有些团队有2个团队成员,有些团队有最大值(8个)

我有这个while循环来读取该行并将值分配给我的构造函数中的对象。我想我应该使用for循环来分配团队成员,但是我在for条件中写了什么,所以我可以分配给团队的对象?

try {
            while(input.hasNext())
            {
                input.nextLine();
                int ID = input.nextInt();
                String teamName = input.next();
                String coachFirst = input.next();
                String coachLast = input.next();
                String mentorFirst = input.next();
                String mentorLast = input.next();
                String teamFs = input.next();
                String teamSS = input.next();

                //for loop?
                input.nextLine();
            }
        }
        catch (NoSuchElementException statException)
        {
            System.out.print("WRONG ELEMT");
        }
        catch (IllegalStateException stateException)
        {
            System.out.print("Wrong state");
        }

文本文件以防任何人需要了解我的问题:

TeamNumber,Team Name,Coach First,Coach Last,Mentor First,Mentor Last,Team Fin Sponsor,Schools or Sponsoring Organization,TmMem1First,TmMem1Last,TmMem2First,TmMem2Last,TmMem3First,TmMem3Last,TmMem4First,TmMem4Last,TmMem5First,TmMem5Last,TmMem6First,TmMem6Last,TmMem7First,TmMem7Last,TmMem8First,TmMem8Last
6842,Reagan Ray-Guns,Judy,Mallon,Aziz,Valdez,Texas Workforce Commission,REAGAN H S,Steven,Cepeda,Alan,Yue,Tim,Callaway,Damon,Bertucci,Samuel,de Olvieira,Samuel,Day,,,,
6888,Islanders,Judy,Maldonado,Brady,Trevino,Three Rivers Robotics,THREE RIVERS MIDDLE,Shireen,Cowdrey,Dee,Roundtree,Steven,Callaway,Francisco,Bermea,,,,,,,,
7004,GREENHILL Tops,Kanat,LaBass,Harvey,Pflueger,GREENHILL Boosters,GREENHILL SCHOOL,Harvey,Pflueger,Sandra,Day,Denny,Rodriguez,shirley,Couvillon,Carly,Szarka,,,,,,
7079,SportBots,Karim,Kramer,Brian,Torres Santos,,HARMONY SCHOOL OF NATURE & ATHLETICS,Steven,Castillo Baca,John,McGaughey,Warren,Aktas,Diane,Barrera,Rebeca,Escamilla,Bert,Eickstead,Jina,Castillejo,Eddy,Romeo

2 个答案:

答案 0 :(得分:0)

检查以下代码。在while循环的每次迭代结束时,您将获得一个新的“newTeam”对象,您可以以任何您想要的方式操作它。每个团队对象都包含一个ArrayList来保存团队成员对象。每个团队成员对象都有firstName和lastName。

我可以扩展会员类来存储教练和导师名字,但不想让你感到困惑。因此,我保持简单。你可以在此基础上继续发展。

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;


public class TeamReader {
    // Nested class for holding the properties of a team
    static class Team{
        // Nested class for holding first and last names of members
        static class Member{
            String firstName, lastName;
            public Member(String fname, String lname){
                this.firstName = fname;
                this.lastName = lname;
            }
        }

        int ID;
        String teamName, coachFirst, coachLast, mentorFirst, mentorLast, sponsor, org;
        ArrayList<Member> members = new ArrayList<Member>();
        public String toString(){
            return Integer.toString(ID)+" - "+teamName;
        }
    }

    public static void main(String[] args) throws IOException {
        //System.out.println(System.getProperty("user.dir"));  Finding current working directory
        File file = new File("input.csv");
        BufferedReader br = new BufferedReader(new FileReader(file));
        String current;
        current = br.readLine();  // Skipping csv header

        while((current = br.readLine())!=null){
            System.out.println(current);
            String[] data = current.split(",");
            Team newTeam = new Team();

            for (int i = 0; i < data.length; i++){
                switch(i){
                case 0:
                    newTeam.ID = Integer.parseInt(data[i]);
                    break;
                case 1: newTeam.teamName = data[i];
                        break;
                case 2: newTeam.coachFirst = data[i];
                        break;
                case 3: newTeam.coachLast = data[i];
                        break;
                case 4: newTeam.mentorFirst = data[i];
                        break;
                case 5: newTeam.mentorLast = data[i];
                        break;
                case 6: newTeam.sponsor = data[i];
                        break;
                case 7: newTeam.org = data[i];
                        break;
                default:newTeam.members.add(new Team.Member(data[i],data[i+1]));
                        i++;
                        break;
                }
            }
            // Do whatever you want with the team
            System.out.println(newTeam);
        }
    }
}

答案 1 :(得分:0)

只需将整个文件一次性读入List<String>,然后浏览List<String>并实例化您的团队。

public static void main(String[] args) {      
    try {
        List<String> myFileLines = Files.readAllLines(Paths.get(yourTextFile));

        List<Team> myTeams = new ArrayList<>();
        for (String line : myFileLines) {
            String[] linePieces = line.split(",");

            Team team = new Team();
            team.TeamNumber = linePieces[0];
            team.TeamName = linePieces[1];
            team.CoachFirst = linePieces[2];
            // etc...

            myTeams.add(team);
        }

        // Do whatever with your list of teams
    } catch (Exception e) {
        // Handle exception
    }
}

public static class Team {
    String TeamNumber,TeamName,CoachFirst,CoachLast,MentorFirst,
            MentorLast,TeamFinSponsor,SchoolsorSponsoringOrganization,
            TmMem1First,TmMem1Last,TmMem2First,TmMem2Last,TmMem3First,
            TmMem3Last,TmMem4First,TmMem4Last,TmMem5First,TmMem5Last,
            TmMem6First,TmMem6Last,TmMem7First,TmMem7Last,TmMem8First,TmMem8Last;
}