640i宝马四门轿跑:JAVA程序编写

来源:百度文库 编辑:查人人中国名人网 时间:2024/04/20 04:10:45
1. Write a program that simulates rolling a pair of dice. You can simulate rolling one die by choosing one of the integers 1, 2, 3, 4, 5, or 6 at random. The number you pick represents the number on the die after it is rolled. You can assign this value to a variable to represent one of the dice that are being rolled. Do this twice and add the results together to get the total roll. Your program should report the number showing on each die as well as the total roll. For example:
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;
}
}