您好,我想知道如何更改显示方法的输出,以便输出,目前看起来像这样:
Leonardo da Vinci
40 seconds ago - 2 people like this.
No comments.
Had a great idea this morning.
But now I forgot what it was. Something to do with flying...
可以看起来像这样
Leonardo da Vinci
Had a great idea this morning.
But now I forgot what it was. Something to do with flying...
40 seconds ago - 2 people like this.
No comments.
这两个方法负责超类
中的部分输出public String toString()
{
String text = username + "\n" + timeString(timestamp);
if(likes > 0) {
text+= " - " + likes + " people like this.\n";
}
else {
text+= "\n";
}
if(comments.isEmpty()) {
return text + " No comments.\n";
}
else {
return text + " " + comments.size() +
" comment(s). Click here to view.\n";
}
}
public void display()
{
System.out.println(toString());
}
这些是子类中的两个方法,它们通过调用上面的超类来完成输出。
public String toString()
{
return super.toString() + message + "\n";
}
/**
* Display the details of this post.
*
* (Currently: Print to the text terminal. This is simulating display
* in a web browser for now.)
*/
public void display()
{
System.out.println(toString());
}
答案 0 :(得分:1)
这是您期望的结果:
Leonardo da Vinci
Had a great idea this morning.
But now I forgot what it was. Something to do with flying...
40 seconds ago - 2 people like this.
No comments.
message
的值是:
Had a great idea this morning.
But now I forgot what it was. Something to do with flying...
super.toString()
的价值:
40 seconds ago - 2 people like this.
No comments.
你的子类toString()返回:
public String toString()
{
return super.toString() + message + "\n";
}
结果是:super.toString():
Leonardo da Vinci
40 seconds ago - 2 people like this.
No comments.
和message
:
Had a great idea this morning.
But now I forgot what it was. Something to do with flying...
你知道为什么按顺序打印吗? 您只需将订单更改为:
return message + super.toString() + "\n";
这将改变它的显示顺序。
并且变量username
中打印的super.toString()
的{{1}}值
答案 1 :(得分:0)
您可以为类中的每个字符串创建单独的方法,并在构建结束字符串时单独调用它们。
例如:
in superclass:
public void display() {
System.out.println(super.getTimeString()+"\n"+message);
//or put whatever in whatever order you want.
}
子类中的:
{{1}}