调用setCustomer方法时遇到问题。 编码如下:
public class Customer {
public int customerID = 001;
public String name ="name required";
public String address ="address required";
public String email ="email required";
public void setCustomer(int custID, String nm , String add ){
}
public void setCustomer(int custID, String nm , String add , String em){
}
public void displayCustomer(){
System.out.println("Customer ID: " +customerID);
System.out.println("Customer Name: " +name);
System.out.println("Customer Address: " +address);
System.out.println("Customer Email: " +email);
}//end of display method
}//end of class
public class CustomerTest {
public static void main(String[] args) {
Customer c1 = new Customer();
Customer c2 = new Customer();
c1.setCustomer(002, "ishihi", "alalalla2");
c2.setCustomer(003, "tututu", "kikiki","rans@g.com");
c1.displayCustomer();
c2.displayCustomer();
}
}
我得到的输出是:
Customer ID: 1
Customer Name: name required
Customer Address: address required
Customer Email: email required
Customer ID: 1
Customer Name: name required
Customer Address: address required
Customer Email: email required
我想在主函数中显示我为c1和c2设置的内容,但它仍然如上所示。
答案 0 :(得分:2)
您的setCustomer
方法为空
public void setCustomer(int custID, String nm , String add ){
}
public void setCustomer(int custID, String nm , String add , String em){
}
实施您想要的行为。
答案 1 :(得分:1)
public void setCustomer(int custID, String nm , String add ){ }
这个方法做得不多,毕竟你的方法体是{}
,所以毫无意外的是它没有效果。编程不会通过魔法改变对象的状态 - 您必须编写代码才能执行此操作。使用设置对象的字段的代码填写{}
,您将看到魔法变为现实。
答案 2 :(得分:0)
您需要在方法中实际设置所有类字段。它们目前是空的,不做任何事情。
public void setCustomer(int custID, String nm , String add ){
customerID = custID;
name = nm;
address = add;
}
public void setCustomer(int custID, String nm , String add , String em){
customerID = custID;
name = nm;
address = add;
email = em;
}
在main
中,使用这些方法。您目前没有给他们打电话:
public static void main(String[] args) {
Customer c1 = new Customer();
c1.setCustomer(1, "name1", "address1", "email1");
Customer c2 = new Customer();
c1.setCustomer(2, "name2", "address2", "email2");
}