简体   繁体   中英

How do I create an array of objects from a class, and then pass those to subclasses?

To start off, I just want to say I am a CS Major and my university has strict rules on any sort of plagiarism , so any answer that doesn't say "try this code" would be greatly appreciated :) using code to explain is fine. Anyways, my question. I just reached a point where I am really trying to understand a sharp learning curve for me. Inheritance and Polymorphism. My textbook explains it very well, and I understand the material, its just applying it to something real is what is getting to me. My assignment in a nutshell reads from a text file which contains a fantasy baseball team (players, and stats of each player) and then outputs a new text file with the team's entire stats. But my confusion is stemming from the following procedures after connecting to the file, which involve passing the scanner onto a class called BaseballTeam , which is aggregated with a superclass called Player , which then has two subclasses. Here is my driver:

public static final String INPUT_FILE = "baseballTeam.txt"; 

public static void main(String[] args) {
    BaseballTeam team = new BaseballTeam();

    Scanner inputStream = null;
    try {
        inputStream = new Scanner(new File(INPUT_FILE));
        team.loadTeam(inputStream);

    } catch (FileNotFoundException e) {
        System.out.println("File " + INPUT_FILE + " Not Found.");
        System.exit(1);

The BaseballTeam class is supposed to create an array of player references as an instance variable, and then the loadTeam() method creates objects for each type of player (pitcher, batter, or sub). After that, the scanner is handed of to a method called loadData() within the Player class, which is then inherited by the other two classes Batter and Pitcher with the same method name. I'm posting my other classes (unfinished/barely started) just in case the structure needs to be referenced. BaseballTeam:

import java.util.Scanner;

public class BaseballTeam {

    private static String name;
    private static final Player roster = new Player[]; 

    BaseballTeam() {
       name = null;
    } 
    public static String getName() {
        return name;
    }

    public static void setName(String aName) {
        name = aName;
    }

    public static void loadTeam (Scanner input) {

    }

    public static void outputTeam() {

    }

    public static int calculateTeamWins() {
        return 0;
    }

    public static int calculateTeamSaves() {
        return 0;
    }

    public static double calculateTeamERA() {
        return 0;
    }

    public static double calculateTeamWHIP() {
        return 0;
    }

    public static double calculateTeamBattingAverage() {
        return 0;
    }

    public static int calculateTeamHomeRuns() {
        return 0;
    }

    public static int calculateTeamRBI() {
        return 0;
    }

    public static int calculateStolenBases(){
        return 0;
    }
}

Player:

import java.util.Scanner;

public class Player {

    private static String name;
    private static String position;

    Player() {        

        name = null;
        position = null;        
    }
    public static String getName() {
        return name;
    }

    public static void setName(String aName) {
        name = aName;
    }

    public static String getPosition() {
        return position;
    }

    public static void setPosition(String aPosition) {
        position = aPosition;
    }  

    public static void loadData(Scanner input) {

    }

    public static String generateDisplayString() {
        return null;
    }
}

Pitcher:

import java.util.Scanner;

public class Pitcher extends Player {

    private static int wins;
    private static int saves;
    private static int inningsPitched;
    private static int earnedRuns;
    private static int hits;
    private static int walks;

    Pitcher() {
        super();
        wins = 0;
        saves = 0;
        inningsPitched = 0;
        earnedRuns = 0;
        hits = 0;
        walks = 0;
    }

    public static int getWins() {
        return wins;
    }

    public static void setWins(int aWins) {
        wins = aWins;
    }

    public static int getSaves() {
        return saves;
    }

    public static void setSaves(int aSaves) {
        saves = aSaves;
    }

    public static int getInningsPitched() {
        return inningsPitched;
    }

    public static void setInningsPitched(int aInningsPitched) {
        inningsPitched = aInningsPitched;
    }

    public static int getEarnedRuns() {
        return earnedRuns;
    }

    public static void setEarnedRuns(int aEarnedRuns) {
        earnedRuns = aEarnedRuns;
    }

    public static int getHits() {
        return hits;
    }

    public static void setHits(int aHits) {
        hits = aHits;
    }

    public static int getWalks() {
        return walks;
    }

    public static void setWalks(int aWalks) {
        walks = aWalks;
    }   

    public static void loadData(Scanner input) {

    }

    public static String generateDisplayString() {
        return null;
    }

    public static double calculateERA() {
        return 0;
    }

    public static double calculateWHIP() {
        return 0;
    }
}

And Batter:

import java.util.Scanner;

public class Batter extends Player {
    private static int atBats;
    private static int hits;
    private static int homeRuns;
    private static int rbi;
    private static int stolenBases;

    Batter() {
        super();
        atBats = 0;
        hits = 0;
        homeRuns = 0;
        rbi = 0;
        stolenBases = 0;
    }

    public static int getAtBats() {
        return atBats;
    }

    public static void setAtBats(int aAtBats) {
        atBats = aAtBats;
    }

    public static int getHits() {
        return hits;
    }

    public static void setHits(int aHits) {
        hits = aHits;
    }

    public static int getHomeRuns() {
        return homeRuns;
    }

    public static void setHomeRuns(int aHomeRuns) {
        homeRuns = aHomeRuns;
    }

    public static int getRbi() {
        return rbi;
    }

    public static void setRbi(int aRbi) {
        rbi = aRbi;
    }

    public static int getStolenBases() {
        return stolenBases;
    }

    public static void setStolenBases(int aStolenBases) {
        stolenBases = aStolenBases;
    }

    public static void loadData(Scanner input){

    }

    public static String generateDisplayString() {
        return null;
    }

    public static double calculateBattingAverage() {
        return 0;
    }
}

Again, I'm not looking for someone to do my program for me, I just need a nudge in the right direction, because I am having a hard time wrapping my head around the other two pillars of object oriented programming. All I know at the moment is I need to have a loop, preferably a do-while within the loadData() so I can sort the players from that stats and the pitchers from the batters. And just because, here is the text file my professor cleverly composed(for sake of brevity he put all the pitchers together, and all the batters together, the other five are just there):

The Amazing Lamps
Mary Hansen
P 2 1 7 2 3 2
Orville Verde
P 1 0 12 5 12 3
David Nilsen
P 0 0 0 0 0 0
Clark Gable
P 2 0 14 2 10 5
Claw Hammer
P 0 2 2 0 1 1
Random Superhero
P 1 1 4 2 3 1
Noodlearm Johnson
P 0 0 1 5 6 3
Rolando Gerner
P 1 0 12 5 7 6
Norbert Shockey
P 0 0 3 0 3 1
Katinka Erdale
P 0 0 2 1 1 0
Charles Babbage
C 12 2 0 0 0
Funky 
1B 19 7 2 4 1
Luke Skywalker
2B 0 0 0 0 1
Sally Field
3B 21 7 1 8 3
Nari Takahashi
SS 22 8 0 3 2
Joe Schmough
OF 20 6 2 5 1
Mary Ennis
OF 19 4 0 2 1
Yvette Crester
OF 15 3 0 1 0
Michael Ellinger
DH 13 5 2 0 0
Alvaro Ochoa
U 6 2 0 0 1
Woodland Being
P
Angel Charley
OF
Professor Trelawny
C
Average Joe
U
Sandy Koufax
P

Also, sorry if this posting goes against any rules for being to lengthy. Just not sure how to really get into the guts of my assignment. To sum up my question, I am getting lost on how to take the data from .txt with my loadTeam() and then separating the pitchers, batters, and subs(players without stats) into their own object, so that I can pass the data down through the subclasses. Creating objects from the array is what is stumping me.

Ultimately, your problem will be easier to solve by using a Java Collection class.

ArrayList<Player> roster = new ArrayList<Roster>();

Based on the sample code you provided, I presume that you need to solve the issue with an array. Your roster will need to construct an array with an appropriate maximum size. It should not be final since you will by dynamically adding values to it. Also, since you might have more than one team, your roster should not be static.

Change

private static final Player roster = new Player[]; 

To private static Player[] roster = new Player[50];

You can add elements to this array and pass roster to other functions. You can read it with a loop.

for(Player player: roster) {...}

Good luck.

Not enough rep to comment (sorry), but to take a guess at what you are trying to do, it sounds like you want to use the scanner to read in the text file and process it within your BaseballTeam class to fill the array of Player s. As the BaseballTeam class is doing the reading and processing, all of your Player s don't need to know about the Scanner - only the class that does the reading needs it.

In your BaseballTeam.loadTeam() method, you probably want to use the scanner to look at the individual lines. Then for every second line (the one that contains the player type), you can look at the first character and use that to decide whether you create a new Batter , Pitcher , or Player , which you can add to roster .

For your Player classes, you can add a constructor with arguments for all the different stats.

eg

public Batter(String name, int wins, int losses, int hits /*etc*/) {

}

Then when you read in a file, you can look at the first char, if it's B, then call new Batter(/*Stats you get from the rest of the line*/) .

package test;

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Scanner;

    public class BaseballTeam {

    private String teamName;
    private List<Player> playersList = new ArrayList<Player>(10);
    private final String PITCHER = "P";
    private final String BATTER = "B";

    BaseballTeam() {
        teamName = null;
    }

    public String getTeamName() {
        return teamName;
    }

    public void setTeamName(String aName) {
        teamName = aName;
    }

    public void loadTeam() throws FileNotFoundException {
        File f = new File("Test.txt");
        Scanner scan = new Scanner(f);
        String playername = "";
        String playerpos = "";
        String playerscore = "";
        while (scan.hasNext()) {
            // first is team name
            int wins = 0;
            int saves = 0;
            int inningsPitched = 0;
            int earnedRuns = 0;
            int hits = 0;
            int walks = 0;
            if (teamName == null) {
                teamName = scan.nextLine();
            }
            if (playername == null || playername.trim().length() == 0) {
                playername = scan.nextLine();
            }
            if (scan.hasNext()) {
                playerscore = scan.nextLine();
            }
            String[] scorelist = playerscore.split(" ");
            String playertype = "";
            if (scorelist.length >= 1) {
                playertype = (scorelist[0]);
            }
            try {
                if (scorelist != null && scorelist.length > 1) {
                    if (scorelist.length >= 2 && scorelist[1] !=   null) {
                        wins = Integer.parseInt(scorelist[1]);
                    }
                    if (scorelist.length >= 3 && scorelist[2] != null) {
                        saves = Integer.parseInt(scorelist[2]);
                    }
                    if (scorelist.length >= 4 && scorelist[3] != null) {
                        inningsPitched = Integer.parseInt(scorelist[3]);
                    }
                    if (scorelist.length >= 5 && scorelist[4] != null) {
                        earnedRuns = Integer.parseInt(scorelist[4]);
                    }
                    if (scorelist.length >= 6 && scorelist[5] != null) {
                        hits = Integer.parseInt(scorelist[5]);
                    }
                    if (scorelist.length >= 7 && scorelist[6] != null) {
                        walks = Integer.parseInt(scorelist[6]);
                    }
                } else {
                    System.out.println("My name is: " + playername
                            + " :: Ooops no players score available");
                }

                if (playertype != null && playertype.contains(PITCHER)) {
                    Player p = new Pitcher(playername, "", wins, saves,
                            inningsPitched, earnedRuns, hits, walks);
                    playersList.add(p);
                    // System.out.println(p.toString());
                } else if (playertype != null && playertype.contains(BATTER)) {
                    playerpos = scorelist[0].substring(0, 1);
                    Player b = new Batter(playername, playerpos, wins, saves,
                            inningsPitched, earnedRuns, hits);
                    playersList.add(b);
                    // System.out.println(b.toString());
                } else {
                    System.out.println(playername
                            + " I am not sure what is my role.");
                }
                playername = "";
            } catch (Exception e) {
                System.out.println("My name is: " + playername
                        + " :Ooops some data problem");
                playername = "";
            }
        }
    }

    public static void outputTeam() {

    }

    public static int calculateTeamWins() {
        return 0;
    }

    public static int calculateTeamSaves() {
        return 0;
    }

    public static double calculateTeamERA() {
        return 0;
    }

    public static double calculateTeamWHIP() {
        return 0;
    }

    public static double calculateTeamBattingAverage() {
        return 0;
    }

    public static int calculateTeamHomeRuns() {
        return 0;
    }

    public static int calculateTeamRBI() {
        return 0;
    }

    public static int calculateStolenBases() {
        return 0;
    }

    @Override
    public String toString() {
        StringBuilder build = new StringBuilder("BaseballTeam [\nteamName="
                + teamName + ", ");
        for (Player player : playersList) {
            build.append(player.toString() + "\n");
        }
        build.append(" ]");
        return build.toString();
    }
    }



Main class

        public class sss {
    public static void main(String[] args) {
        BaseballTeam team = new BaseballTeam();

        try {
            // inputStream = new Scanner(new File(INPUT_FILE));
            team.loadTeam();
            System.err.println("***************************");
            System.err.println(team.toString());
        } catch (Exception e) {
            e.printStackTrace();
            // System.out.println("File " + " Not Found.");
            System.exit(1);
        }
    }
    }

Pitcher class

     package test;

     public class Pitcher extends Player {

    private int wins;
    private int saves;
    private int inningsPitched;
    private int earnedRuns;
    private int hits;
    private int walks;

    public Pitcher(String name, String position, int wins, int saves,
            int inningsPitched, int earnedRuns, int hits, int walks) {
        super(name, position);
        this.wins = wins;
        this.saves = saves;
        this.inningsPitched = inningsPitched;
        this.earnedRuns = earnedRuns;
        this.hits = hits;
        this.walks = walks;
    }

    public int getWins() {
        return wins;
    }

    public void setWins(int aWins) {
        wins = aWins;
    }

    public int getSaves() {
        return saves;
    }

    public void setSaves(int aSaves) {
        saves = aSaves;
    }

    public int getInningsPitched() {
        return inningsPitched;
    }

    public void setInningsPitched(int aInningsPitched) {
        inningsPitched = aInningsPitched;
    }

    public int getEarnedRuns() {
        return earnedRuns;
    }

    public void setEarnedRuns(int aEarnedRuns) {
        earnedRuns = aEarnedRuns;
    }

    public int getHits() {
        return hits;
    }

    public void setHits(int aHits) {
        hits = aHits;
    }

    public int getWalks() {
        return walks;
    }

    public void setWalks(int aWalks) {
        walks = aWalks;
    }

    public void loadData() {

    }

    public double calculateERA() {
        return 0;
    }

    public double calculateWHIP() {
        return 0;
    }

    @Override
    public String toString() {
        return "Pitcher [I am pitcher my name is: " + name
                + " my details : wins=" + wins + ", saves=" + saves
                + ", inningsPitched=" + inningsPitched + ", earnedRuns="
                + earnedRuns + ", hits=" + hits + ", walks=" + walks + "]";
    }
    }

Player class.

       package test;

     public class Player {
    protected String name;
    protected String position;

    protected Player() {
    }

    protected Player(String name, String position) {
        this.name = name;
        this.position = position;
    }

    public String getName() {
        return name;
    }

    public void setName(String aName) {
        name = aName;
    }

    public String getPosition() {
        return position;
    }

    public void setPosition(String aPosition) {
        position = aPosition;
    }

    }


 Batter Class

       package test;

       public class Batter extends Player {
    private int atBats;
    private int hits;
    private int homeRuns;
    private int rbi;
    private int stolenBases;

    public Batter() {
        super();
    }

    public Batter(String name, String position, int atBats, int hits,
            int homeRuns, int rbi, int stolenBases) {
        super(name, position);
        this.atBats = atBats;
        this.hits = hits;
        this.homeRuns = homeRuns;
        this.rbi = rbi;
        this.stolenBases = stolenBases;
    }

    public int getAtBats() {
        return atBats;
    }

    public void setAtBats(int aAtBats) {
        atBats = aAtBats;
    }

    public int getHits() {
        return hits;
    }

    public void setHits(int aHits) {
        hits = aHits;
    }

    public int getHomeRuns() {
        return homeRuns;
    }

    public void setHomeRuns(int aHomeRuns) {
        homeRuns = aHomeRuns;
    }

    public int getRbi() {
        return rbi;
    }

    public void setRbi(int aRbi) {
        rbi = aRbi;
    }

    public int getStolenBases() {
        return stolenBases;
    }

    public void setStolenBases(int aStolenBases) {
        stolenBases = aStolenBases;
    }

    public void loadData() {

    }

    public String generateDisplayString() {
        return null;
    }

    public double calculateBattingAverage() {
        return 0;
    }

    @Override
    public String toString() {
        return "I am a Batter my name is " + name + " [atBats=" + atBats
                + ", hits=" + hits + ", homeRuns=" + homeRuns + ", rbi=" +  rbi
                + ", stolenBases=" + stolenBases + "]";
    }
}

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