gpt4 book ai didi

Java 对象构造函数返回 "null"

转载 作者:行者123 更新时间:2023-12-01 09:57:36 28 4
gpt4 key购买 nike

Java 新手! 我创建了一个具有各个字段的构造函数的类。但是,当我尝试打印字段时,我收到“null”作为输出。请帮助我理解为什么。这是类(class):`

 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());
}

我做错了什么?预先感谢您!

`

最佳答案

相反,而不是:

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

关于Java 对象构造函数返回 "null",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37063877/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com