首页 > 解决方案 > 我的数组成员为空,即使它们已初始化

问题描述

所以我试图访问我的关系数组中的成员,一旦它被初始化。但是它不允许我这样做。我究竟做错了什么?

public class FamilyRelations {
private Relationship [] relation;

public static void main(String[] args) {

    FamilyRelations family = new FamilyRelations(); 

    Scanner scanner = new Scanner(test);
    family.run(scanner);    
}

private void run(Scanner scanner) {


    noOfRelations = 3;
    relation= new Relationship [3];
    System.out.println(relation[0].child); // Why does this raise nullpointerexception?
     // Here I want to do relation[0].father = "John"; for example



}

public class Relationship {

public String child;
public String father;
public String mother;

public Relationship() {
    this.child = "hej";
    this.father = "father";
//  this.mother = mother;
}

标签: java

解决方案


推荐阅读