我在嘗試將數組對象分配給另一個數組時遇到了NPE。我在這裏做錯了什麼?NPE卡住將Array.toString(對象)分配給另一個數組中的類
這是我的工作代碼:
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)
抱歉,這是一個嚴重的代碼和一個嚴重的措辭問題。 –