Java 从类方法内部创建数组以供对象使用
目标:从可用于对象的“if语句”创建数组 这是代码。我想使用laneChoice()方法来确定要创建哪个数组,我计划使用更多的“else-if”语句。但目前,我一直得到一个NullPointerException,我认为原因是私有字符串[]匹配没有更新Java 从类方法内部创建数组以供对象使用,java,arrays,Java,Arrays,目标:从可用于对象的“if语句”创建数组 这是代码。我想使用laneChoice()方法来确定要创建哪个数组,我计划使用更多的“else-if”语句。但目前,我一直得到一个NullPointerException,我认为原因是私有字符串[]匹配没有更新 private String[] Matchup; 将laneChoice方法更改为 public String[] laneChoice(){ if(lane.equals("TOP")){ Matchup
private String[] Matchup;
将
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语句的范围。当你说
返回匹配
,匹配
引用类中声明的尚未初始化的数组。因此,会发生NullPointerException
。需要在if语句之外声明数组
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;
}