以下是我创建的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方法,允许我在每一行之后更改消息体。
答案 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;
}
收件人同样如此。