java - 我需要将instanceof与来自不同类的arraylist一起使用

标签 java arraylist instanceof

嗨,我的问题是我有一个包含soccerPlayer和BaseballPlayer的数组列表,但我需要寻找棒球玩家并获得具有最高BattingAvg的棒球玩家我不知道如何使该方法成为可能这是我的棒球玩家类和我的MainClass.. .谢谢

这是我的棒球运动员类(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()); 
    }
}

这是我的主要类(class)

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

谢谢

最佳答案

参见Martin8768's回答如何解决您眼前的问题。您应该意识到,使用 instanceof 并不被认为是非常面向对象的,因此应尽可能避免。另一种方法需要您退一步考虑:

Is there a similar calculation for SoccerPlayer that I can generalize?

如果是这样,您可以在 Player 上创建一个抽象方法,SoccerPlayer 和 BaseBallPlayer 都可以有具体的实现。然后您可以简单地在 Player 上调用该方法:

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

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

关于java - 我需要将instanceof与来自不同类的arraylist一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9476136/

相关文章:

angular - 从 Angular 的 mat-table 中显示的数组列表中删除对象

java - 我的 2D ArrayList 输出给出累积值?

java - 如何获取列表中特定类型的所有对象?

javascript - 序列化包含不同类型的数组

java - 在 jfreechart 库中获取带有文本格式的条形图

java - Android 应用程序在 Lollipop 上崩溃 - 服务 Intent 必须明确 :

java - JSF 2.x + Spring 3.2 集成?

java - 如何将自定义类的 ArrayList 转换为 Java 中的 JsonArray?

javascript - 如何理解类型 `new (...args: any[]) => any`

java - 错误 : Failed to resolve: com. google.girebase :firebase-core:16. 2.0