黑马程序员技术交流社区
标题:
面向对象编程题疑惑
[打印本页]
作者:
up_
时间:
2012-10-25 13:34
标题:
面向对象编程题疑惑
import java.util.Random;
//5.用用面向对象的思想实现如下的骰子游戏:丢下两个骰子,若分值的总值为7点,则赢;否则输。public class Test4 {
public static void main(String[] args){
DiceGame c=new DiceGame();
c.play();
Die d=new Die();
d.roll();
Random r=new Random();
int a=r.nextInt(6)+1;
int b=r.nextInt(6)+1;
System.out.println(a+" "+b);
d.getFaceValue(a,b);
}
}
class DiceGame{
int Die1;
int Die2;
void play(){
System.out.println("开始啦");
}
}
class Die{
int faceValue;
static void roll(){
System.out.println("请投掷骰子");
}
static void getFaceValue(int a,int b){
int faceValue=a+b;
if(faceValue==7){
System.out.println("您赢啦");
}else{
System.out.println("很抱歉,您输了");}
}
}//用面向的思维应该怎样改写该代码.
作者:
王永荣
时间:
2012-10-25 14:06
你要想万物皆对象。把掷骰子游戏看成一个对象,它有开始、判断输赢等功能。
这里是我的一点拙见。。因为我也是刚开始学的。
代码如下,主要是用到了面向对象的封装性。
import java.util.Random;
public class Test4 {
public static void main(String[] args){
Game g= new Game(); //创建了一个Game类的对象g
g.play();
g.roll();
int a =g.random();
int b = g.random();
System.out.println(a+" "+b);
g.getFaceValue(a,b);
}
}
class Game{
void play()
{
System.out.println("Start!");
}
void roll(){
System.out.println("请投掷骰子");
}
int random(){
Random r = new Random();
return r.nextInt(6)+1;
}
void getFaceValue(int a,int b){
int faceValue=a+b;
if(faceValue==7)
System.out.println("您赢啦");
else
System.out.println("很抱歉,您输了");
}
}
复制代码
作者:
付维翔
时间:
2012-10-25 14:21
以下是我的想法,分离出两个对象,一个是游戏窗口本身对象,另一个是骰子对象,两者是组合关系。因为游戏中我们可以更换骰子,因此从面对象来考虑,两者互为组合关系。
以下是我的代码设计:
public class DiceGame {
private Dice dice1;
private Dice dice2;
public DiceGame(Dice dice1, Dice dice2) {
this.dice1 = dice1;
this.dice2 = dice2;
}
// 更换骰子(比如骰子在游戏中找不到,需要更换一个)
public void setDice1(Dice dice1) {
this.dice1 = dice1;
}
public void setDice2(Dice dice2) {
this.dice2 = dice2;
}
public void gameStar() {
System.out.println("游戏开始,掷下两个骰子");
dice1.roll();
dice2.roll();
System.out.println("两个骰子的值分别为:" + dice1.getFaceValue() + "、"
+ dice2.getFaceValue());
int value = dice1.getFaceValue() + dice2.getFaceValue();
if (value == 7)
System.out.println("您赢啦");
else
System.out.println("很抱歉,您输了");
}
public static void main(String[] args) {
Dice dice1 = new Dice();
Dice dice2 = new Dice();
DiceGame game = new DiceGame(dice1, dice2);
game.gameStar();
System.out.println("骰子1掉下水道去了(可能是马路上玩的)");
Dice dice3 = new Dice();// 拿来一个新骰子
game.setDice1(dice3);// 在游戏中使用新骰子
// 游戏再次开始
game.gameStar();
}
}
复制代码
package cn.zuhe;
import java.util.Random;
// 骰子对象
public class Dice {
private int faceValue = 1;// 筛子的值
Random r = new Random();
// 获取骰子的值
public int getFaceValue() {
return faceValue;
}
// 掷骰子的方法
public void roll() {
faceValue = r.nextInt(6) + 1;
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2