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
}
}
}
不知道你说的是random类还是math.random,所以写了两个
1. Math.random
public class Test1 {public static void main(String[] args) {
int a, b
a = (int)(1+Math.random()*(6))
b = (int)(1+Math.random()*(6))
while (a != b) {
System.out.println("Not equal! a=" + a + ", b=" + b)
a = (int)(1+Math.random()*(6))
b = (int)(1+Math.random()*(6))
}
System.out.println("Equal! a=b=" + a)
}
}
2. random类
import java.util.Randompublic class Test2 {
public static void main(String[] args) {
int a, b
Random ra = new Random()
a = ra.nextInt(6)+1
b = ra.nextInt(6)+1
while (a != b) {
System.out.println("Not equal! a=" + a + ", b=" + b)
a = ra.nextInt(6)+1
b = ra.nextInt(6)+1
}
System.out.println("Equal! a=b=" + a)
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)