广东科技职业学院:JAVA程序编写
来源:百度文库 编辑:神马品牌网 时间:2024/05/13 13:56:51
The first die comes up 3
The second die comes up 5
Your total roll is 8
2.Write a class named PairOfDice. An object of this class will represent a pair of dice. It will contain two instance variables to represent the numbers showing on the dice and an instance method for rolling the dice. Your instance variables must be private, and you must test your class with a short program that counts how many times a pair of dice is rolled, before the total of the two dice is equal to two.
能做出来,我再加分,保证做到
问题1的源代码如下:
public class RollTheDices {
public static void main(String[] args) {
int die1;
int die2;
int roll;
die1 = (int)(Math.random()*6) + 1;
die2 = (int)(Math.random()*6) + 1;
roll = die1 + die2;
System.out.println("The first die comes up " + die1);
System.out.println("The second die comes up " + die2);
System.out.println("Your total roll is " + roll);
}
}
问题2的源代码如下:
public class PairOfDice {
private int die1;
private int die2;
public static void main(String[] args) {
int numberOfRolls;
PairOfDice pairDice = new PairOfDice();
numberOfRolls = pairDice.rollFor(2);
System.out.println("It took " + numberOfRolls + " rolls before the total of the two dice is equal to two.");
}
public int rollFor(int n) {
int roll;
int rollCt;
rollCt = 0;
do {
die1 = (int)(Math.random()*6) + 1;
die2 = (int)(Math.random()*6) + 1;
roll = die1 + die2;
rollCt++;
} while (roll != n);
return rollCt;
}
}