如何调试Java消息输出始终为null的原因?

时间:2016-09-20 02:51:03

标签: java class methods printing null

以下是我创建的Message课程:

public class Message {
  static String toString;
  static String sender;
  static String recipient; 
  static String messageBody ;

  public Message(String Sender, String Recipient){
    sender = Sender ;
    recipient = Recipient ;
    messageBody = "";
  }

  public String getSender(String s){
    sender = s;
    return sender;  
  }
  public String getRecipient(String r){
    recipient = r;
    return recipient;   
  }
  public void append (String a){
    a = messageBody +a; 
  }
  public void toString (String m){
    messageBody = m;
    m = ("From: " + sender + "\nTo: "+ recipient+"\n" + "\n" + messageBody);
    System.out.print(m);
  }
}

以下是main方法。我需要使用toString()方法进行打印。

import java.util.Scanner;

public class Lab8 {
  public static void main(String[] args) {
  // TODO Auto-generated method stub
    Message mess1 = new Message (null, null);       
    Scanner keyboard = new Scanner (System.in);
    String Sender1= Message.sender; 
    String recipient1 = Message.recipient;
    String message = Message.messageBody ;

    System.out.println ("Input Sender Name: ");
    Sender1 = keyboard.next();
    System.out.println ("Input Recipent Name: ");
    recipient1 = keyboard.next();
    do {
      System.out.print ("Input Message: ");
      message = keyboard.next();
    } while (!message.equals("***") );

    System.out.print(Message.toString);
  }
}

每次打印null。我还需要包含append方法,允许我在每一行之后更改消息体。

1 个答案:

答案 0 :(得分:2)

你错了! 没有必要有一个名为toString的静态字符串字段,您只需要toString()方法。但是,您不需要在toString()方法中打印任何内容。只需从中返回一个String。

按如下方式更改toString方法:

public String toString (String m) {
  messageBody = m;
  m = ("From: " + sender + "\nTo: "+ recipient+"\n" + "\n" + messageBody);
  return m;
}

然后打印它,在主方法中使用以下代码行:

System.out.print(mess1.toString(message));

尽管如此,你的吸气者和二传手都错了。尝试阅读有关getter和setter的更多信息。

应该有两种方法:

  • getSender()
  • setSender()

getSender()应如下所示:

public String getSender(){
  return sender;  
}

并且setSender()应如下所示:

public void setSender (String sender) {
  this.sender = sender;
}

收件人同样如此