Java新手! 我创建了一个具有各种字段构造函数的类。但是,当我尝试打印字段时,我收到了#34; null"作为输出。请帮我理解原因。这是班级:`
public class User {
//All relevant information to identify each user.
private String FirstName;
private String LastName;
private String Email;
private long PhoneNum;
private long CardNum;
//Build Constructors for User info.
public User(String Fname, String Lname, String Mail, long num, long card)
{
Fname=FirstName;
Lname=LastName;
Mail=Email;
num=PhoneNum;
card=CardNum;
}
//Method to set FirstName.
public void setFirstName (String Fname)
{
FirstName=Fname;
}
//Method to get FirstName.
public String getFirstName()
{
return FirstName;
}
//Method to set LastName.
public void setLastName (String Lname)
{
LastName=Lname;
}
//Method to get Lastname.
public String getLastname()
{
return LastName;
}
//Method to set email.
public void setEmail (String Mail)
{
Email=Mail;
}
//Method to get email.
public String getEmail()
{
return Email;
}
//Method to set phonenumber.
public void setPhoneNum(long num)
{
PhoneNum=num;
}
//Method to get phonenumber.
public long getPhoneNum()
{
return PhoneNum;
}
//Method to set credit card number.
public void setCardNum(long card)
`enter code here`{
CardNum=card;
}
// Method to get credit card number.
public long getCardNum()
{
return CardNum;
}
现在,当我运行此代码时,我会收到" null":
public class UserDemo {
public static void main(String[] args)
{
String first="Matt";
String last="Burns";
String email="mburns267@yahoo.com";
long phone=333;
long card=222;
User Matt=new User(first,last,email,phone,card);
System.out.print(Matt.getLastname());
}
我做错了什么?提前谢谢!
`
答案 0 :(得分:1)
是相反的,而不是:
public User(String Fname, String Lname, String Mail, long num, long card){
Fname=FirstName;
Lname=LastName;
Mail=Email;
num=PhoneNum;
card=CardNum;
}
它应该是:
public User(String Fname, String Lname, String Mail, long num, long card){
FirstName = Fname;
LastName = Lname;
Email = Mail;
PhoneNum = num;
CardNum = card;
}
要避免此类事情,您可以使用this
关键字。这是一个例子:
String firstName;
public Constructor(String firstName){
this.firstName = firstName;
}
答案 1 :(得分:0)
您的构造函数分配方式错误:
public User(String Fname, String Lname, String Mail, long num, long card)
{
// this refers to the current object being constructed
this.FirstName = Fname;
this.LastName = Lname;
this.Email = Mail;
this.PhoneNum = num;
this.CardNum = card;
}
答案 2 :(得分:0)
应该像这样创建Java构造函数对象:
public User(String Fname, String Lname)
{
this.firstName = Fname;
//keyword 'this' refers to the new object, so the new object's Fname would equal the firstName place below
this.lastName = Lname; //same as above
}
要创建新用户,请使用以下代码:
User Matt = new("Matt", "Burns"); //Creates a new User Matt, with firstName "Matt" and lastName "Burns"
System.out.println(Matt.getfirstName()); //prints User Matt's firstName to the console.