微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 Java TreeMap/继承访问父函数

如何解决使用 Java TreeMap/继承访问父函数

我可能只是忽略了一些东西,但我正在研究团队课程,需要计算球员的投球和击球统计数据。 TreeMap 花名册是使用球员构建的,因此它可以容纳投手和位置球员。我需要能够从 Pitcher 和 Position player 调用一些函数,但 TreeMap 只允许我访问 Player 函数。如何访问其他功能?我曾尝试将玩家移动到正确类型的其他 TreeMap 中,但它说该类无法转换。此外,只是循环尝试调用所需的函数。由于覆盖调用 toString() 方法,程序知道它们是 Pitchers 或 PositionPlayers。只是好奇如何以最少的处理访问这些其他方法

Cannot find symbol错误

开始就是问题出现的地方。我意识到 Player 类没有这些功能,这就是范围,但我不确定如何解决这个问题。

    public String calcHittingStats(){
        int count = 0;
        int totAtBats = 0;
        int totRunsBattedIn = 0;
        int totHomeRuns = 0;
        int totHitByPitch = 0;
        double totBattingAvg = 0.0;
        double totOnBasePercent = 0.0;
        
        for(Map.Entry<Integer,**Player**> player : hitters.entrySet()){
            totAtBats += player.getValue()**.getAtBats()**;
            totRunsBattedIn += player.getValue()**.getRunsBattedIn()**;
            totHomeRuns += player.getValue()**.getHomeRuns()**;
            totHitByPitch += player.getValue()**.getHitByPitch**();
            totBattingAvg += player.getValue()**.getBattingAverage**();
            totOnBasePercent += player.getValue()**.getonBasePercent**();
            count++;
        }
        totBattingAvg = totBattingAvg / count;
        totOnBasePercent = totOnBasePercent / count;
        return " ";
    }

UML for the code

解决方法

您必须使用 instanceof 来检查类型。

在此之后转换为专用类型并分配给另一个局部变量。使用新的正确类型变量,您可以调用专用方法和字段。

这是一个简单但有效的示例(您可以运行它):

package temp;

import java.util.Map;
import java.util.TreeMap;

public class TeamPlayGround {

    public static void main(String[] args) {
        new TeamPlayGround().test();
    }

    private void test() {
        Team team = new Team();
        
        team.roster.put(1,new Pitcher("My-Pitcher"));
        team.roster.put(2,new PositionPlayer("My-PosPlayer1"));
        
        /* now iterate over the players: */
        for (Player player :team.roster.values()) {
            /* use instanceof to check for type at runtime */
            if (player instanceof Pitcher) {
                /* its an pitcher so cast it...*/
                Pitcher pitcher = (Pitcher) player;
                pitcher.doPitcherOperation();
            }
            /* same for position player */
            if (player instanceof PositionPlayer) {
                PositionPlayer positionPlayer = (PositionPlayer) player;
                positionPlayer.doPositionPlayerOperation();
            }
        }
        
    }
    
    private class Team{
        Map<Integer,Player> roster = new TreeMap<>();
    }
    
    private class Player{
        String name;
    }
    
    private class Pitcher extends Player{
        
        public Pitcher(String name) {
            this.name=name;
        }
        
        public void doPitcherOperation() {
            System.out.println(name + " is doing pitch operation");
        }
        
    }

    private class PositionPlayer extends Player{
        
        public PositionPlayer(String name) {
            this.name=name;
        }
        
        public void doPositionPlayerOperation() {
            System.out.println(name + " is doing position player operation");
        }
        
    }
    
}
,

这是这个问题的主要解决方案:

if(player.getValue().getClass() == Pitcher.class){
Pitcher pitcher = (Pitcher) player.getValue();

我不确定这是否被认为是好的,但它有效。这是整个功能:

    public String calcPitchingStats(){
        int count = 0;
        int totInnings = 0;
        int totEarnedRuns = 0;
        double totEarnedRunAvg = 0.0;
        double totWhip = 0.0;

        for(Map.Entry<Integer,Player> player : roster.entrySet()){
            if(player.getValue().getClass() == Pitcher.class){
                
                Pitcher pitcher = (Pitcher) player.getValue();
                totInnings += pitcher.getInningsPitched();
                totEarnedRuns += pitcher.getEarnedRuns();
                totEarnedRunAvg += pitcher.getEarnedRunAverage();
                totWhip += pitcher.getWhip();
                count++;
            }
        }

        totEarnedRunAvg = totEarnedRunAvg / count;
        totWhip = totWhip / count;
        return "Total Innings: " + totInnings + " Total Earned Runs: " +
                totEarnedRuns + " Total Earned Run Average: " + totEarnedRunAvg
                + " Total Whip: " + totWhip;
    }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。