将返回值分配给新变量(Java)
发布时间:2020-12-15 04:42:13 所属栏目:Java 来源:网络整理
导读:自从我做了一些 java编码以来已经有一段时间了. 我需要为需要自动化的业务(研讨会的一部分)构建一个应用程序,但这与我的问题无关…… 我被困在线上:customerList.add(客户); //(WCIA类中的addCustomer方法的一部分) 这也是我第一次被告知“将返回值分配给新
|
自从我做了一些
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;
}
}
解决方法
您需要先实例化ArrayList,然后才能为其分配元素.您可能正在获得NullPointerException,这是我的猜测.
改变这一行: private final ArrayList customerList = null; 至 private final ArrayList customerList = new ArrayList(); 至少应该解决这个问题.我没有阅读你的其余代码所以我不确定是否存在其他问题. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
