我需要使用instanceof与来自不同类的arraylist

时间:2012-02-28 03:54:06

标签: java arraylist instanceof

我的问题是我有一个带有soccerPlayer和BaseballPlayer的arrayList,但是我需要查找baseballPlayer并获得带有highestBattingAvg的baseballPlayer我不知道如何使该方法成为可能这是我的BaseballPlayer类和我的MainClass ..谢谢你

这是我的BASEBALLPLAYER CLASS

    package HomeWork7;

public class BaseballPlayer extends Player{

    private int atBat, hits;

    public BaseballPlayer(String sp, String t, String pos,
            String f_name, String l_name, int ab, int h) {
        super(sp, t, pos, f_name, l_name);
        atBat = ab;
        hits = h;
    }

    public double battingAverage() {
        return ((double)hits/atBat);
    }

    public String toString() {
        return super.toString() + " Position: " + super.getPos() 
        + " Batting Avg: " + String.format("%3.3f", battingAverage()); 
    }
}

这是我的主要课程

 package HomeWork7;

import java.io.*;
import java.util.*;

public class PlayersMain 
{
    private ArrayList<Player> theplayer = new ArrayList<Player>();
    Scanner in;
    PrintWriter out;


    public void openFiles()
    {
    try
        {
            File input = new File("Players.txt");
            in = new Scanner(input);

            File output = new File("output.txt");
            out = new PrintWriter(output);      
        }
    catch (FileNotFoundException ex) 
        {
        System.err.println("File not found!");
        ex.printStackTrace();
        }
    }

    public void readData()
    {
        String sport, team, pos, fn, ln;
        int goalsScored;
        int goalsAllowed;
        int minutes;
        int atBats;
        int hits;
        double innings;
        int earnedRuns;

        while(in.hasNext())
        {
          sport = in.next();
          team = in.next();
          pos = in.next();
          fn = in.next();
          ln = in.next();

          if (sport.equalsIgnoreCase("soccer"))
          {
            minutes = in.nextInt();
            goalsScored = in.nextInt();

            if (pos.equalsIgnoreCase("goalie"))
            {
                goalsAllowed = in.nextInt();
                Goalie g = new Goalie(sport,team,pos,fn,ln,minutes,goalsScored,goalsAllowed);
                theplayer.add(g);
            }
            SoccerPlayer socc = new SoccerPlayer(sport,team,pos,fn,ln,minutes,goalsScored);
            theplayer.add(socc);
          }

          else if (sport.equalsIgnoreCase("Baseball"))
          {
              atBats = in.nextInt();
              hits = in.nextInt();

              if(pos.equalsIgnoreCase("Pitcher"))
              {
                  innings = in.nextDouble();
                  earnedRuns = in.nextInt();
                  Pitcher pit = new Pitcher(sport,team,pos,fn,ln,atBats,hits,innings,earnedRuns);
                  theplayer.add(pit);
              }
              BaseballPlayer base = new BaseballPlayer(sport,team,pos,fn,ln,atBats,hits);
              theplayer.add(base);

          }
        }
    }

  /**
   * close the files that are been used in the program
   * the output file and the input file
   */
  public void closeFiles()
  {
    in.close();
    out.close();
  }

  public BaseballPlayer getHighBattingAverage()
  {

    if(something instanceof BaseballPlayer)
    {
        //i do not know how to do this how to initialize this of something
//and then make it work please i need help the array list already have the information
//how i make it check from each one what is baseball player and what is not i know i need a for loop but i am stuck please help
    }

  }

  public Goalie getLowestAvgGoalsAllowed()
  {
    return null;

  }

  public void displayPlayers(ArrayList<Player> list)
  {
      openFiles();

        for(Player e: list)
        {
          out.println(e.getPosition() + ": " + e.getName());
        }

        closeFiles();
  }
    public static void main(String[] args) {
        PlayersMain pm = new PlayersMain();
        pm.openFiles();      //opens the input and output files
        pm.readData();       //reads the data file and populates the arraylist
        BaseballPlayer b = pm.getHighBattingAverage();
        System.out.println(b);
        Goalie g = pm.getLowestAvgGoalsAllowed();
        System.out.println(g);
        pm.displayPlayers(); //output all players in the arraylist to the file
        pm.closeFiles();     //close input and output files
    }
}

谢谢你

3 个答案:

答案 0 :(得分:4)

请参阅Martin8768's答案,了解如何解决您的直接问题。您应该知道使用instanceof不被认为是面向对象的,应尽可能避免使用。另一种方法要求您退后一步并考虑:

  

我是否可以对SoccerPlayer进行类似的计算   概括

如果是这样,你可以在Player上创建一个抽象方法,SoccerPlayer和BaseBallPlayer都可以为其实现具体实现。然后你可以在Player上调用该方法:

for(Player player : allPlayers) { 
   PlayerStatistics playerStats = player.calculatePlayerStatistics();
}

请注意添加了一种新类型PlayerStatistics - 可用于以通用方式存储有用信息。

答案 1 :(得分:3)

增强for循环是您希望实现的。

for(Player player : theplayer) {
    if(player instanceof BaseballPlayer) {
        //put stuff here
    }
}

答案 2 :(得分:0)

我可以看到您知道如何对列表中的每个对象执行某些操作,如displayPlayers()中所示。听起来你想对列表中的每个玩家做的事情就像是“检查这个玩家是否是迄今为止击球率最高的棒球运动员,如果是这样,请记住该球员。”