有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

字符串未添加到Java列表中

我有一个问题,我发送字符串变量到,从,主题,消息和附件到服务器,当我去把他们在一个列表中,消息变量总是空的!我已经输出了变量消息,它给出了它应该是什么,但是一旦我把它放入列表中。它显示为空

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

共 (2) 个答案

  1. # 1 楼答案

    有两件事正在发生。正如@Dilip指出的,构造函数初始化中有一个错误

    此外,attachment显然是一个空字符串

    因此,在ctor中,字符串字段message被分配一个空字符串,字符串字段attachment未初始化,因此null

    在Java中,toString()将空值打印为字符串文本“null”

    “”作为局部变量message的值打印,“null”作为局部变量attachment的值打印

    这说明了为什么对局部变量、函数参数和字段使用相同的名称可能是危险的

    此外,对于这种抽象来说,使用字符串作为附件(可能是字符串,也可能不是字符串,具体取决于您的实现)可能是一个糟糕的选择

  2. # 2 楼答案

    您的Emailconstructor中存在问题。使用messageattachment两次分配message字段