在执行这个游戏时,最后屏幕上显示的是如下图所示。 甲虫情况变成了Beetle@60aeb0。

原来在System.out.println(beetle)中实际上用到了toString方法,为了清楚表达甲虫的情况,要重写这一方法。
在Beetle类中加入下面重写的toSting()方法:
public String toString() {
if(body) {
String result = "你的甲虫现在有了一处躯干!";
if(head) {
if(eyes > 0) {
result +="\n你的甲虫现在有了一只眼睛";
} else {
result +="";
}
if(eyes == 2) { result +="\n你的甲虫现在有二只眼睛!";}
}
return result;
}
}
现在再运行,显示效果就清楚些了:

上面显示的还是有些麻烦,重写toString方法,用字符表示一只甲虫如何?
把上面的代码改为:
public String toString() {
if(body) {
String result = "";
if(head) {
if(eyes > 0) {
result +="o"; //小o表示一只眼
} else {
result +="";
}
result += "O" //大O表示两只眼睛中间的修饰部分
if(eyes == 2) { result +="o";}
}
return result;
}
}
最终效果如下:

至此,甲虫游戏完成了!
448

被折叠的 条评论
为什么被折叠?



