мне нужно использовать instanceof с arraylist из другого класса - PullRequest
0 голосов
/ 28 февраля 2012

Привет, моя проблема в том, что у меня есть arrayList с soccerPlayer и BaseballPlayer, но мне нужно найти baseballPlayer и получить baseballPlayer с самым высокимBattingAvg. Я не знаю, как сделать этот метод возможным, это мой класс BaseballPlayer и мой MainClass ..Спасибо

Это мой класс игроков

    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 ]

4 голосов
/ 28 февраля 2012

См. Ответ Мартина8768 о том, как решить вашу непосредственную проблему. Вы должны знать, что использование instanceof не считается объектно-ориентированным, и его следует избегать, когда это возможно. Альтернативный подход требует от вас отступить и рассмотреть:

Есть ли аналогичный расчет для SoccerPlayer, который я могу обобщать?

и, если это так, вы можете создать абстрактный метод на Player, для которого как SoccerPlayer, так и BaseBallPlayer могут иметь конкретные реализации. Затем вы можете просто вызвать этот метод в Player:

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

Обратите внимание на добавление нового типа PlayerStatistics, который можно использовать для хранения полезной информации в общем виде.

3 голосов
/ 28 февраля 2012

расширенный цикл for - это то, что вы хотите реализовать

for(Player player : theplayer) {
    if(player instanceof BaseballPlayer) {
        //put stuff here
    }
}
0 голосов
/ 28 февраля 2012

Я вижу, что вы знаете, как что-то сделать с каждым объектом в списке, как в displayPlayers().Похоже, что то, что вы хотите сделать с каждым игроком в списке, это что-то вроде «проверьте, является ли этот игрок бейсбольным игроком с самым высоким средним уровнем пока что, и если да, то запомните этого игрока».

...