本帖最后由 黑马王双 于 2013-6-8 13:13 编辑
题目:用用面向对象的思想实现如下的骰子游戏:丢下两个骰子,若分值的总值为7点,则赢;否则输。
代码:
一,
public class Test3 {
public static void main(String[] args){
DieGame dieGame = new DieGame();
if (dieGame.play()) {
System.out.println("你赢了!");
} else {
System.out.println("你输了!");
}
}
}
class Die {
private int faceValue;
// public int getFaceValue() {
// return faceValue;
// }
// public void setFaceValue(int faceValue) {
// this.faceValue = faceValue;
// }
public int roll() {
this.faceValue = (int) (Math.random() * 6 + 1);
return faceValue;
}
}
class DieGame{
private Die die1 = new Die();
private Die die2 = new Die();
public boolean play() {
die1.roll();
System.out.println("第一次点数:" + die1.roll());
die2.roll();
System.out.println("第二次点数:" + die2.roll());
if (die1.roll() + die2.roll() == 7) {
return true;
} else {
return false;
}
}
}
二,
public class Test3 {
public static void main(String[] args){
DieGame dieGame = new DieGame();
if (dieGame.play()) {
System.out.println("你赢了!");
} else {
System.out.println("你输了!");
}
}
}
class Die {
private int faceValue;
public int getFaceValue() {
return faceValue;
}
public void setFaceValue(int faceValue) {
this.faceValue = faceValue;
}
public void roll() {
this.faceValue = (int) (Math.random() * 6 + 1);
}
}
class DieGame{
private Die die1 = new Die();
private Die die2 = new Die();
public boolean play() {
die1.roll();
System.out.println("第一次点数:" + die1.getFaceValue());
die2.roll();
System.out.println("第二次点数:" + die2.getFaceValue());
if (die1.getFaceValue() + die2.getFaceValue() == 7) {
return true;
} else {
return false;
}
}
}
下面的二设置了set和get,这个到底有什么作用,和一方法比较有什么不同?
|