字符串未添加到列表-Java
我有一个问题,我发送字符串变量到,从,主题,消息和附件到服务器,当我去把他们在一个列表中,消息变量总是空的!我已经输出了变量消息,它给出了它应该是什么,但是一旦我把它放入列表中。它显示为空字符串未添加到列表-Java,java,Java,我有一个问题,我发送字符串变量到,从,主题,消息和附件到服务器,当我去把他们在一个列表中,消息变量总是空的!我已经输出了变量消息,它给出了它应该是什么,但是一旦我把它放入列表中。它显示为空 private void doSend(String name) { String to = input.nextLine(); String from = input.nextLine(); String subject = input.nextLine(); String
private void doSend(String name)
{
String to = input.nextLine();
String from = input.nextLine();
String subject = input.nextLine();
String message = input.nextLine();
String attachment = input.nextLine();
System.out.println(to);
System.out.println(from);
System.out.println(subject);
System.out.println(message);
System.out.println(attachment);
// stores the message, but not into the mailbox
MultiEchoServer.MailBox.add(new Email(to, from,subject, message, attachment));
System.out.println(MailBox);
System.out.println("Message Sent to: " + to);
System.out.println(message);
}
样本输出
pj // this is the to variable
dsds // this is the from variable
subject // this is the subject variable
message // this is the message variable
[pj dsds subject null] //this is the Mailbox List
Message Sent to: pj //not part of the error
message // this is the message variable being outputted again to see it it changed
我甚至不确定是否有人可以帮助我,但如果您需要查看更多代码,请告诉我,谢谢
电子邮件类
class Email
{
private String to, from, subject, message, attachment;
int id;
public Email(String to ,String from ,String subject, String message, String attachment)
{
this.to = to;
this.from = from;
this.subject = subject;
this.message = message;
this.message = attachment;
}
public int id()
{
return(id);
}
public String to()
{
return(to);
}
public String from()
{
return(from);
}
public String subject()
{
return(subject);
}
public String message()
{
return(message);
}
public String attachment()
{
return(attachment);
}
public String toString()
{
return(to + " " + from + " " + subject + " " + message + "" + attachment);
}
}
您的
电子邮件中有问题
类构造函数
。您使用消息和附件两次分配消息
字段您的电子邮件
类构造函数中存在问题。您使用消息
和附件
两次分配消息
字段有两件事。正如@Dilip指出的,构造函数初始化中有一个错误
此外,附件
显然是一个空字符串
因此,在ctor中,字符串字段消息
被分配一个空字符串,字符串字段附件
未初始化,因此为空
在Java中,toString()
将空值打印为字符串文本“null”
“”作为局部变量消息的值打印,而“null”作为局部变量附件的值打印
这说明了为什么对局部变量、函数参数和字段使用相同的名称可能是危险的
此外,对于这种抽象来说,使用字符串作为附件(可能是字符串也可能不是字符串,具体取决于您的实现)可能是一个糟糕的选择。有两种情况。正如@Dilip指出的,构造函数初始化中有一个错误
此外,附件
显然是一个空字符串
因此,在ctor中,字符串字段消息
被分配一个空字符串,字符串字段附件
未初始化,因此为空
在Java中,toString()
将空值打印为字符串文本“null”
“”作为局部变量消息的值打印,而“null”作为局部变量附件的值打印
这说明了为什么对局部变量、函数参数和字段使用相同的名称可能是危险的
此外,使用字符串作为附件(可能是字符串也可能不是字符串,具体取决于您的实现)可能是一个糟糕的抽象选择。显示toString()
邮箱类的方法的代码?因此,问题可能出在Email类中,也可能出在邮箱类中。给我们看看他们的代码。您还应该学会使用调试器,并自己解决这个问题;this.message=附件;您正在通过附件覆盖邮件。@AniketThakur:它与问题绝对相关。>与您的问题无关,但this.message=attachment
实际上,这与问题有关,因为它可能会将message设置为null
。显示MailBox
类的toString()方法的代码?因此,问题可能在Email类中,或者可能在MailBox类中。给我们看看他们的代码。您还应该学会使用调试器,并自己解决这个问题;this.message=附件;您正在通过附件覆盖邮件。@AniketThakur:它与问题绝对相关。>与您的问题无关,但this.message=attachment
实际上,这与问题有关,因为它可能会将消息设置为null
。