将返回值分配给新变量(Java)

时间:2014-02-08 19:03:22

标签: java

自从我做了一些java编码以来已经有一段时间了。

我需要为需要自动化(研讨会的一部分)的业务构建应用程序,但这与我的问题无关......

我被困在线上:customerList.add(客户); //(WCIA类中的addCustomer方法的一部分) 这也是我第一次被告知“将返回值分配给新变量”作为错误的一部分,所以不太确定这意味着什么。

代码:主要

    import java.util.ArrayList;


public class WCIA {

    private final ArrayList customerList = null;

    public static void main(String[] args) {

        short s =002;


        Customer arno = new Customer();
        arno.setName("Arno");
        arno.setId(s);
        arno.setEmail("arnomeye@gmail.com");
        arno.setAddress("Somewhere");
        arno.setPhoneNum("0727855201");
         System.out.printf("%s",arno.getEmail());
     WCIA wcia = new WCIA();

     wcia.addCustomer(arno);
     wcia.displayCustomers();
    }

    public void addCustomer (Customer customer)
    {
        customerList.add(customer); // <---Problem over here
    }
    public void displayCustomers()
    {
        for(int x=0;x<customerList.size();x++)
        {
            Customer cus = (Customer) customerList.get(x);
            cus.DisplayCustomer();
        }
    }
}

代码:客户类:

    public class Customer {

   private short id;
   private String name;
   private String email;
   private String phoneNum;
   private String address;

  public Customer()
  {

    System.out.println("Class initiated");
  }




    public void DisplayCustomer()
    {
        System.out.append("Name : "+ name+"\n");
        System.out.append("ID : "+ id+"\n");
        System.out.append("Email : "+ email+"\n");
        System.out.append("Phone Number : "+ phoneNum+"\n");
        System.out.append("address : "+ address+"\n");
    }

    public void setId(short id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public void setPhoneNum(String phoneNum) {
        this.phoneNum = phoneNum;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public short getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getEmail() {
        return email;
    }

    public String getPhoneNum() {
        return phoneNum;
    }

    public String getAddress() {
        return address;
    }

}

3 个答案:

答案 0 :(得分:9)

您需要先实例化ArrayList,然后才能为其分配元素。你可能得到NullPointerException,这是我的猜测。

更改此行:

private final ArrayList customerList = null;

private final ArrayList customerList = new ArrayList();

至少应该解决这个问题。我没有阅读你剩下的代码所以我不确定是否存在其他问题。

答案 1 :(得分:1)

customerListnull且从未初始化。创建一个ArrayList类型的对象,并在尝试添加该变量之前将其分配给该变量。

答案 2 :(得分:1)

您应该声明List明确定义其元素类型(parametrized list):

private final List<Customer> customerList;

这样您就可以{/ 3}}到Customer

Customer cus = customerList.get(x);

最后,作为一种好的做法,在构造函数中初始化它:

public WCIA()
{
    customerList = new ArrayList<>();
}