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;
}
}
}
错误:线程“main”java.lang.NullPointerException中的异常 at workPoS.main(workPoS.java:12)
这是第12行:
some_list[x].firstName = "John";
似乎我能够访问some_list [x],但是只要我指定一个构造函数some_list [x] .firstName,结果就是一个空值。
我只是错误地引用了构造函数值吗? 如果是这样,这样做的正确方法是什么?
谢谢你们!
答案 0 :(得分:7)
看这里:
dataList[] some_list = new dataList[10];
for (int x = 0; x < some_list.length; x++) {
some_list[x].firstName = "John";
您已经创建了数组 - 但所有元素都是空引用。你谈到“错误地引用构造函数值” - 你根本不是调用构造函数。你应该:
for (int x = 0; x < some_list.length; x++) {
some_list[x] = new dataList();
some_list[x].firstName = "John";
有关详细信息,请参阅Java Tutorial for Arrays。
(您还应该修改您的名称以遵循Java命名约定,并将您的字段设为私有,但这是另一回事......)
答案 1 :(得分:0)
如果您在同一个.java文件中同时使用这两个类,请尝试使用此代码
import java.io。*;
public class workPoS {
public workPoS() { super();
}
/ ** * @param args * / public static void main(String [] args){ workPoS wp = new workPoS(); dataList [] some_list = new 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; } }
}