-4

Goal: create an array from an 'if statement' that I can use for my object.

Here is the code. I want to use the method laneChoice() to determine which array to create, I plan on using more 'else if' statements. but for the time being, I keep getting a NullPointerException Which i assume that the reason being that private String[] Matchup is not updating?

    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]);
    }
twokdavey
  • 37
  • 6

1 Answers1

0

Change the laneChoice method to

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

What you are currently doing is creating an array in the if statement. However, that array goes out of scope outside the if statement. When you say return Matchup;, Matchup refers to the array declared in the class, which has not been initialized. Therefore, NullPointerException occurs.

Sweeper
  • 213,210
  • 22
  • 193
  • 313