Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从类方法内部创建数组以供对象使用_Java_Arrays - Fatal编程技术网

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

Java 从类方法内部创建数组以供对象使用,java,arrays,Java,Arrays,目标:从可用于对象的“if语句”创建数组 这是代码。我想使用laneChoice()方法来确定要创建哪个数组,我计划使用更多的“else-if”语句。但目前,我一直得到一个NullPointerException,我认为原因是私有字符串[]匹配没有更新 private String[] Matchup; 将laneChoice方法更改为 public String[] laneChoice(){ if(lane.equals("TOP")){ Matchup

目标:从可用于对象的“if语句”创建数组

这是代码。我想使用laneChoice()方法来确定要创建哪个数组,我计划使用更多的“else-if”语句。但目前,我一直得到一个NullPointerException,我认为原因是私有字符串[]匹配没有更新

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