简体   繁体   中英

having a for-loop inside a while-loop to read specifically from file?

I have a text file that has multiple teams. all teams have different variables but different values. But towards the end of the line, some teams have 2 team members and some have the max(which is 8)

i have this while-loop to read through the line and assign values into my constructors for objects. i think i should use a for-loop to assign the team members, but what do i write in the for condition so i could assign for the object of team?

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");
        }

Text file in case anybody needs to understand my question:

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

Check the below code. At the end of each iteration of the while loop, you'll get a new "newTeam" object, which you can manipulate in whatever way you want. Each team object contains an ArrayList to hold the team members objects. Each team member object has a firstName and a lastName.

I could have extended the Member class for storing the coach and mentor names, but didn't want to confuse you. Hence, I've kept it simple. You can build upon this.

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);
        }
    }
}

Just read the whole file in at once into a List<String> then go through the List<String> and instantiate your teams.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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