`
viMory
  • 浏览: 56680 次
  • 性别: Icon_minigender_1
  • 来自: 土卫六
最近访客 更多访客>>
社区版块
存档分类
最新评论

Beetle游戏改进版

    博客分类:
  • j2se
阅读更多

        在执行这个游戏时,最后屏幕上显示的是如下图所示。 甲虫情况变成了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;
    }
}

最终效果如下:

至此,甲虫游戏完成了!

5
2
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics