目标:使用'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]);
}
答案 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
发生。