Write a class that should have the following name ,field and methods: LastNameFi
ID: 3599272 • Letter: W
Question
Write a class that should have the following name ,field and methods:
LastNameFirstNameDice
-sideUp: int
+ LastNameFirstNameDice()
+roll():void
+getSideUp():int
Write a program that uses the Dice class to play a simple dice game between the computer and the user. The program should create two instances of the Dice class. One Dice object is the computer’s dice , and the other Dice object is the user’s dice (each a 6-sided dice).
The program should have a loop that iterates 10 times. Each time the loop iterates, it should roll both dice. The dice with the highest value wins. (In case of a tie , there is no winner for that particular roll of the dice).
As the loop iterates, the program should keep count of the number of times the computer wins, and the number of times that the user wins. After the loop performs all of its iterations, the program should display who was the grand winner, the computer or the user.
The sideUP field will hold each possible sides of the dice that is facing up. ( 1 thr 6)
The constructor randomly determines the side of the dice that is facing up (1,2,…,6) and initialized the sideUP field accordingly.
roll method that simulates the rolling of the dice. When the roll method is called, it randomly determines the side of the dice that is facing up and sets the sideUP field accordingly.
getSideUp method return the value of the sideUp field.
LastNameFirstNameDice
-sideUp: int
+ LastNameFirstNameDice()
+roll():void
+getSideUp():int
Explanation / Answer
Please find my implementation.
#############
import java.util.Random;
public class LastNameFirstNameDice {
private int sideUp;
private static Random random = new Random();
LastNameFirstNameDice() {
sideUp = random.nextInt(6)+1; //1-6
}
public void roll() {
sideUp = random.nextInt(6)+1; //1-6
}
public int getSideUp() {
return sideUp;
}
}
##############
public class DiceGame {
public static void main(String[] args) {
// User Dice Object
LastNameFirstNameDice user = new LastNameFirstNameDice();
// computer dice object
LastNameFirstNameDice computer = new LastNameFirstNameDice();
int userWin = 0, compWin = 0;
int i=0;
while(i < 10) {
user.roll();
computer.roll();
if(user.getSideUp() > computer.getSideUp())
userWin++;
else if(user.getSideUp() < computer.getSideUp())
compWin++;
i++;
}
if(userWin > compWin) {
System.out.println("user won");
}
else if(userWin < compWin) {
System.out.println("computer won");
}else{
System.out.println("tie!!");
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.