如何从类创建对象数组,然后将它们传递给子类?

时间:2014-09-08 23:36:27

标签: java arrays inheritance file-io polymorphism

首先,我只想说我是CS专业,我的大学对任何类型的抄袭有严格的规定,所以任何答案都不会说“试试这个代码“将非常感激:)使用代码解释很好。无论如何,我的问题。我刚刚达到了一个点,我真的想要了解一个敏锐的学习曲线。继承与多态。我的教科书解释得非常好,而且我理解这些材料,它只是将它应用于真实的东西是我的想法。简而言之,我的任务是从一个文本文件中读取,该文件包含一个幻想棒球队(玩家和每个玩家的统计数据),然后输出一个新的文本文件和团队的整个统计数据。但是我的困惑源于连接到文件后的以下过程,其中涉及将扫描程序传递到名为BaseballTeam的类,该类与名为Player的超类聚合,后者具有两个子类。这是我的司机:

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

BaseballTeam类应该创建一个玩家引用数组作为实例变量,然后loadTeam()方法为每种类型的玩家(投手,击球手或子)创建对象。之后,扫描程序将被移交给loadData()类中名为Player的方法,该方法由其他两个类BatterPitcher继承,方法相同名称。我正在发布我的其他类(未完成/几乎没有启动),以防需要引用结构。 的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;
    }
}

播放器:

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

投手:

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

和击球手:

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

同样,我不是在寻找有人为我做我的程序,我只是需要在正确的方向上轻推,因为我很难绕过面向对象编程的其他两个支柱。我现在所知道的只是我需要一个循环,最好是在loadData()内进行一次,所以我可以根据统计数据和击球手的投手来排序。只是因为,这是我的教授聪明地编写的文本文件(为了简洁起见,他将所有的投手放在一起,所有的击球手都在一起,其他五个就在那里):

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

另外,对不起,如果这个帖子违反任何冗长的规则。只是不确定如何真正进入我的任务的胆量。总结一下我的问题,我迷失了如何从我的loadTeam()获取.txt的数据然后将投手,击球手和潜艇(没有统计数据的球员)分成他们自己的对象,这样我就可以通过子类传递数据。从数组中创建对象是让我感到难过的。

3 个答案:

答案 0 :(得分:1)

最终,使用Java Collection类可以更轻松地解决您的问题。

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

根据您提供的示例代码,我假设您需要使用数组来解决问题。您的名单需要构建一个具有适当最大大小的数组。它不应该是最终的,因为您将动态地向其添加值。此外,由于您可能拥有多个团队,因此您的名单不应该是静态的。

更改

private static final Player roster = new Player[]; 

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

您可以向此数组添加元素并将名单传递给其他函数。你可以用循环阅读它。

for(Player player: roster) {...}
祝你好运。

答案 1 :(得分:1)

没有足够的回复评论(抱歉),但为了猜测你想要做什么,听起来你想使用扫描仪读取文本文件并在BaseballTeam内处理它用于填充Player s数组的类。当BaseballTeam班级正在进行阅读和处理时,您Player的所有人都不需要知道Scanner - 只有阅读和需要它的班级需要它。

BaseballTeam.loadTeam()方法中,您可能希望使用扫描仪查看各行。然后,对于每第二行(包含播放器类型的那一行),您可以查看第一个字符并使用它来决定是否创建新的BatterPitcherPlayer ,您可以将其添加到roster

对于Player类,您可以为所有不同的统计信息添加一个带有参数的构造函数。

e.g。

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

}

然后,当您在文件中阅读时,您可以查看第一个字符,如果它是B,则调用new Batter(/*Stats you get from the rest of the line*/)

答案 2 :(得分:0)

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 + "]";
    }
}