当我尝试将一个数组对象分配给另一个数组时,我陷入了 NPE。我在这里做错了什么?
这是我正在使用的代码:
import java.util.Scanner;
import java.util.Arrays;
public class groupData {
public static void main(String[] args) {
Group students = new Group(4);
students.promtNewUser();
}
}
class Group {
Scanner input = new Scanner(System.in);
private int user_count;
private int max_users;//maximum number of users
private String[] directory;//array for list of users
private String[] user;//array for ind users
//constructor method
public Group(int total_users) {
max_users = total_users;//max_users equals value passed to class with new
user_count = 0;
String[] directory = new String[max_users];
}
public void promtNewUser() {
String[] user = new String[4];
System.out.print("Enter first name: ");
String fname = input.nextLine();
user[0] = fname;
System.out.print("Enter last name: ");
String lname = input.nextLine();
user[1] = lname;
System.out.print("Enter phone number: ");
String phone = input.nextLine();
user[2] = phone;
System.out.print("Enter age: ");
String age = input.nextLine();
user[3] = age;
add_user(user);
}
public void add_user(String[] user) {
if (user_count == max_users) {
System.out.println("Sorry, the group is full!");
}
else {
directory[user_count] = Arrays.toString(user);
System.out.println("User added to group!");
user_count++;
}
}
}
这是根据提示编译并运行后终端的输出:
Enter first name: Winston
Enter last name: Churchill
Enter phone number: +44 1 3425 9989 834
Enter age: 143
Exception in thread "main" java.lang.NullPointerException
at Group.add_user(groupData.java:53)
at Group.promtNewUser(groupData.java:45)
at groupData.main(groupData.java:8)
最佳答案
在您的Group
类中,您指定一个String[]目录
class Group {
// ...
private String[] directory;//array for list of users
然后在您的 Group
构造函数中,声明一个具有相同名称的新局部变量,从而有效地隐藏类变量:
//constructor method
public Group(int total_users) {
// ...
String[] directory = new String[max_users];
当您构造Group
时,类变量永远不会被初始化并保持null
,并且局部变量被创建、分配但从未使用。然后稍后您尝试索引类 directory
变量,但它是 null
:
public void add_user(String[] user) {
if (user_count == max_users) {
System.out.println("Sorry, the group is full!");
}
else {
directory[user_count] = Arrays.toString(user); // HERE: directory is null
System.out.println("User added to group!");
user_count++;
}
}
通过初始化类变量而不是局部变量来修复Group
构造函数:
//constructor method
public Group(int total_users) {
max_users = total_users;//max_users equals value passed to class with new
user_count = 0;
directory = new String[max_users]; // removed the String[] type, so you are now referencing the class variable
}
关于java - 卡在 NPE 将 Array.toString(object) 分配给类中的另一个数组上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42193840/