import java.io.*;

public class workPoS {

    /**
     * @param args
     */
    public static void main(String[] args) {
        dataList[] some_list = new dataList[10];

        for (int x = 0; x < some_list.length; x++) {
            some_list[x].firstName = "John";
            some_list[x].middleName = "Jacob";
            some_list[x].lastName = "Jingle-Heimer-Schmidt";
            some_list[x].age = 101;
        }

        for (int x = 0; x < some_list.length; x++) {
            System.out.println(some_list[x].firstName + " "
                    + some_list[x].middleName + " " + some_list[x].lastName
                    + " Age: " + some_list[x].age);
        }

    }

    public class dataList {
        String firstName, middleName, lastName;
        int age;

        public dataList() {
            firstName = "";
            middleName = "";
            lastName = "";
            age = 0;
        }
    }

}


错误:线程“主”中的异常java.lang.NullPointerException
    在workPoS.main(workPoS.java:12)

这是第12行:

some_list[x].firstName = "John";


看来我能够访问some_list [x],但是一旦我指定了构造函数some_list [x] .firstName,结果就是空值。

我是否只是错误地引用了构造函数值?
如果是这样,正确的方法是什么?

谢谢你们!

最佳答案

如果您在同一个.java文件中使用两个类,请尝试以下代码


  导入java.io. *;
  
  公共类workPoS {

public workPoS() {
  super();

  
  }
  
  / **
       * @参数args
       * /
      公共静态void main(String [] args){
        workPoS wp = new workPoS();
        dataList [] some_list =新的dataList [10];

    for (int x = 0; x < some_list.length; x++) {
      some_list[x] = wp.new dataList();
        some_list[x].firstName = "John";
        some_list[x].middleName = "Jacob";
        some_list[x].lastName = "Jingle-Heimer-Schmidt";
        some_list[x].age = 101;
    }

    for (int x = 0; x < some_list.length; x++) {
        System.out.println(some_list[x].firstName + " "
                + some_list[x].middleName + " " + some_list[x].lastName
                + " Age: " + some_list[x].age);
    }

}

public class dataList {
    String firstName, middleName, lastName;
    int age;

    public dataList() {
        firstName = "";
        middleName = "";
        lastName = "";
        age = 0;
    }
}

  
  }

07-24 14:59