这是我的代码:
public String display() {
return "\n......................\nFixed Employee:\n" +
"Name: " + super.fullName() +
"\nSalary: " + salary() +
" tk\n......................";
}
但是当我从主类调用此方法时,“\ n”newLine无效。只显示一行输出。你会帮助解决这个问题吗?
由于
答案 0 :(得分:10)
要保存文件,请使用\r\n
。 \n
因为新行在打印流上是可行的,但不能写入文件。
答案 1 :(得分:2)
您可能需要独立于系统的行分隔符,因为它可能因操作系统而异。只需将 \ n 替换为行分隔符的值:
public String display() {
String separator = System.getProperty("line.separator"); // Load the system property using its key.
return "\n......................\nFixed Employee:\n"
+ "Name: "
+ super.fullName() +
"\nSalary: "
+ salary()
+ " tk\n......................"
.replace("\\n", separator); // replace the \n before returning your String
}
System#lineSeparator
方法作为@Deepanshu Bedi建议: public String display() {
String separator = System.lineSeparator(); // Consider it as a shortcut.
return "\n......................\nFixed Employee:\n"
+ "Name: "
+ super.fullName() +
"\nSalary: "
+ salary()
+ " tk\n......................"
.replace("\\n", separator); // replace the \n before returning your String
}