嗨,我是 Java 的新手,我有大约 2 个月的经验,所以请尝试使用与我的学习水平相关的术语和代码来回答我的问题。
所以,我必须为学校制作一个程序,让它符合以下格式:
Dear recipient name:
blank line
first line of the body
second line of the body
. . .
last line of the body
blank line
Sincerely,
blank line
sender name
我的代码如下所示:
private String body;
private String letter;
public Letter(String from, String to)
{
letter = ("Dear " + to + ":" + "\n" + "\n" + body + "\n" + "Sincerely," + "\n" + "\n" + from);
body = "";
}
public void addLine(String line)
{
body = body + line + "\n";
}
public String getText()
{
return letter;
}
我尝试了几种不同的方法来完成这个程序,产生最好结果的方法就是这个。问题是,我们最多只能使用两个实例字段。似乎它是空的,因为在我的构造函数中没有给 body 一个值。还有一个程序测试器类,如下所示:
public class LetterTester
{
public static void main(String [] args)
{
Letter tyler = new Letter("Mary", "John");
tyler.addLine("I am sorry we must part.");
tyler.addLine("I wish you all the best.");
System.out.println(tyler.getText());
}
}
我跳过了所有默认的东西和一些大括号,没有语法错误,但是当我运行测试器类时,我得到:
Dear John:
null
Sincerely,
Mary
我做错了什么,有人可以就如何摆脱null给出解决方案吗?请记住,我只能使用两个实例字段,谢谢。