从类方法内部创建数组以供对象使用

时间:2016-12-22 01:09:37

标签: java arrays

目标:使用'if语句'创建一个可用于我的对象的数组。

这是代码。我想使用方法laneChoice()来确定要创建的数组,我打算使用更多'else if'语句。但暂时,我一直得到一个NullPointerException,我认为原因是私有String [] Matchup没有更新?

    private String[] Matchup;

public class ChampionAnalysis {
    private String lane;
    private int aggression;
    private String tankOrDps;
    private String damageType;
    private int mechanics;
    private String champion=null;
    private String[] Matchup;

    public ChampionAnalysis(String lane, int aggression, String tankOrDps, String damageType, int mechanics) {
        this.lane = lane;
        this.aggression = aggression;
        this.tankOrDps = tankOrDps;
        this.damageType = damageType;
        this.mechanics = mechanics;

    }

    public String[] laneChoice(){
        if(lane.equals("TOP")){
            String[] Matchup = new String[] {"Aatrox", "Camille","Cho'Gath","Darius","Dr.Mundo","Galio","Garen","Gnar"
                    ,"Hecarim","Illaoi","Jarvan IV","Kled","Malphite", "Maokai","Nasus","Nautilus","Olaf"
                    ,"Poppy","Renekton","Shen","Shyvana","Singed","Sion","Trundle","Udyr","Vladimir","Volibear"
                    ,"Wukong","Yorick","Zac"};

        }
            return Matchup; 
    }

    public String toString(){
        return (Matchup[1]);
    }

1 个答案:

答案 0 :(得分:0)

laneChoice方法更改为

public String[] laneChoice(){
    if(lane.equals("TOP")){
        Matchup = new String[] {"Aatrox", "Camille","Cho'Gath","Darius","Dr.Mundo","Galio","Garen","Gnar"
                ,"Hecarim","Illaoi","Jarvan IV","Kled","Malphite", "Maokai","Nasus","Nautilus","Olaf"
                ,"Poppy","Renekton","Shen","Shyvana","Singed","Sion","Trundle","Udyr","Vladimir","Volibear"
                ,"Wukong","Yorick","Zac"};

    }
        return Matchup; 
}

您目前正在做的是在if语句中创建一个数组。但是,该数组超出了if语句之外的范围。当您说return Matchup;时,Matchup引用类中声明的数组,该数组尚未初始化。因此,NullPointerException发生。