坚持NPE将Array.toString(对象)分配给Class中的另一个数组

时间:2017-02-12 22:06:02

标签: java arrays class

我在尝试将数组对象分配给另一个数组时卡在NPE上。我在这里做错了什么?

以下是我正在使用的代码:

eewer \n \n ss dffdfdf df df sdf

}

以下是编译并运行提示后终端中的输出:

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++;   
      }

  }

1 个答案:

答案 0 :(得分:1)

Group班级中指定String[] directory

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
}