Tony Stark Tony Stark - 6 months ago 14x
Java Question

simple two players dice throwing game

I'm a first year uni student from Monash Univeristy. We were asked to come up with code that can represent a simple two players dice throwing game (specifications are given below). I know as a matter of fact that there are many areas upon which my code could be improved. However, rather than asking other people to correct my code, I would much prefer to be given hints or general principles as to how my code could be improved. I think I could get more out of this exercise this way. So could someone please provide me with some comments or suggestions? Critics of any level and kind are welcomed! Feel free to pick apart my code! Thanks in advance for any help!

Game class:

import java.util.Scanner;

public class Game {

private Player p1;
private Player p2;
private Dice dice;
private int scoreToWin;

void displayGameMenu() {
System.out.println("(1) Start a new game");
System.out.println("(2) Play one round");
System.out.println("(3) Who is leading now?");
System.out.println("(4) Display game help");
System.out.println("(5) Exit game");
System.out.print("Choose an option: ");

void selectGameOption(int optionSelected) {
switch (optionSelected) {
case 1:
case 2:
case 3:
case 4:

void startNewGame() {
String p1Name;
String p2Name;

Scanner sc = new Scanner(;
System.out.print("Please enter player one name: ");
p1Name = sc.nextLine();
System.out.print("Please enter player two name: ");
p2Name = sc.nextLine();
System.out.print("Please enter the maximum score required to win: ");
scoreToWin = sc.nextInt();

p1 = new Player(p1Name);
p2 = new Player(p2Name);
dice = new Dice();

void playOneRound(Player p) {
int result;

int firstDiceRoll = dice.rollDice();
int secondDiceRoll = dice.rollDice();
if (firstDiceRoll == secondDiceRoll) {
result = (firstDiceRoll + secondDiceRoll) * 2;
System.out.printf("%s rolled %d and %d, "
+ "and scored %d points(BONUS DOUBLE POINTS), "
+ "for a total of %d points",
p.getName(), firstDiceRoll, secondDiceRoll,
result, p.getTotalScore()
} else {
result = (firstDiceRoll + secondDiceRoll);
System.out.printf("%s rolled %d and %d, "
+ "and scored %d points, "
+ "for a total of %d points",
p.getName(), firstDiceRoll, secondDiceRoll,
result, p.getTotalScore()


void whoIsLeading() {
if (p1.getTotalScore() == p2.getTotalScore()) {
System.out.format("Its currently a draw, "
+ "%s has %d, %s has %d",
p1.getName(), p1.getTotalScore(),
p2.getName(), p2.getTotalScore()
} else if (p1.getTotalScore() > p2.getTotalScore()) {
System.out.printf("%s is leading, %s has %d points, "
+ "%s has %d points",
p1.getName(), p1.getName(), p1.getTotalScore(),
p2.getName(), p2.getTotalScore());
} else if (p1.getTotalScore() < p2.getTotalScore()) {
System.out.format("%s is leading, %s has %d points, "
+ "%s has %d points.",
p2.getName(), p2.getName(), p2.getTotalScore(),
p1.getName(), p1.getTotalScore()

void displayGameInstruction() {
System.out.println("All players roll a dice twice per turn.");
System.out.println("If 2 dice rolls have the same value, the player scores 2 times the sum two dice rolls.");
System.out.println("If 2 dice rolls have different values, the player simply scores the sum of two dice rolls.");
System.out.println("For each player, result is incremented after each turn.");
System.out.println("First player to reach or exceed the maxScore wins the game");


boolean checkIfAnyoneHasWon() {
if (p1.getTotalScore() >= scoreToWin && p2.getTotalScore() >= scoreToWin) {
System.out.println("Its a draw! Both players have exceeded the score limit");
return true;
} else if (p1.getTotalScore() >= scoreToWin && p2.getTotalScore() < scoreToWin) {
System.out.format("%s won", p1.getName());
return true;
} else if (p1.getTotalScore() < scoreToWin && p2.getTotalScore() >= scoreToWin) {
System.out.format("%s won", p2.getName());
return true;
return false;

public static void main(String[] args) {
System.out.println("Welcome to the Dice and Roll game!");

Game game = new Game();

int optionSelected;

while (true) {
Scanner sc = new Scanner(;
optionSelected = sc.nextInt();

while (optionSelected > 5 || optionSelected < 0) {

System.out.print("Option entered invalid, please enter a number from 1 to 5: ");
optionSelected = sc.nextInt();

if (optionSelected == 5) {
System.out.println("Exiting game");


boolean anyoneWin = game.checkIfAnyoneHasWon();
if (anyoneWin) {
System.out.println("Game ended.");


Player class:

public class Player {
private final String name;
private int totalScore;

Player(String name){ = name;

String getName(){
return name;

int getTotalScore(){
return totalScore;

void setTotalScore(int score){
totalScore += score;


Dice class:

import java.util.Random;

public class Dice {

private final static int numberOfSides = 6;

int rollDice() {

int result;
Random randomNumberGenerator = new Random();
result = randomNumberGenerator.nextInt(numberOfSides) + 1;
return result;

Program specification:

For this assignment you will write a program that simulates a rather
simplistic Dice Throwing Game. This section specifies the required
functionality of the program. Only a text interface is required for
this program; however, more marks will be gained for a program that is
easy/intuitive to use, with clear information/error messages to the

The aim of the Dice Throwing Game is to simulate a simple game
for 2 players, where they take turn to each roll a dice twice, and
score points according to the results of the dice rolls. The winner is
the one who accumulates a pre-defined maximum score first. Your
program will display a menu which allows the user of the program to
select various options to simulate the various operations. Results of
all the operations will be printed on the screen as plain text only
(eg. “Andy rolled 5 + 3, and scored 8 points”).

The “dice rolls” are
simulated by the program, using some random number generator. The
program will update each player's current score accordingly. For this
assignment, the program will only handle TWO players. It will keep
track of the current score of the players until one, or both, reaches
the pre-defined maximum score, agreed upon at the start of the game.

Program Logic:

The Dice Throwing Game begins with a welcome message followed by a
menu with the following options :

Option (1) asks the 2 players to
enter their names. A player’s name must not be blank (or consists of
only spaces and nothing else), but may contain spaces between the
characters. If this option is chosen again after the players have
already been set up, 2 "new" players are set up (ie. with 2 new names,
and both their starting scores set to 0). Note that the new players
replace the previous players – there are only ever two players at any
one time.

After the names are set up, the game asks for a maximum
score. The default maximum score should be set to 200 points. Each
player’s initial score is set to 0.

Option (2) simulates the “dice
roll” operations for both players. When this option is chosen, the
computer generates 4 random numbers between 1-6 (ie. simulating a
6-sided dice), representing 2 dice rolls for each player. It then
updates both players' scores accordingly. The scoring rules for each
"round" are as follows :

 if the 2 dice rolls have the same value
(ie. 1&1, 2&2, …, 6x6), the player scores 2 times the sum of that
value (eg. 1&1 scores 4 points, 2&2 scores 8 points, etc)

 if the 2
dice rolls have different values, the player simply scores the sum of
that value (eg. 1&4 scores 5 points, 5&2 scores 7 points, etc)

 if
both players reaches a score which is more than the pre-defined
maximum, the game’s result is a Draw. note that both players can
reach over that score at the same time, since for each round, 2 dice
rolls are performed for each player, before a winner is decided

 a
player is considered a winner if he accumulates a score which is more
than the pre-defined maximum, and the other player has not reached
that score

Option (3) shows the players current scores, including who
is leading the game.

Option (4) displays some brief instructions
regarding how to play the game.

Option (5) exits the whole program.
All player statistics should be cleared.

Additional Notes :

The menu must be displayed repeatedly after each operation, until the
user chooses Option (5). Inputs other than 1-5 should be rejected,
with appropriate error messages printed.

If the user chooses Option
(2)/(3), before a game has been set up (Option (1)), an appropriate
error message should be printed, and the operation aborted.

program must deal with invalid values entered by the user in a
sensible manner.


I'll get this in hopefully before the question is closed:

1) Re-read the prompt, you've missed some things in the instructions:

  • You don't check if a new game has started and output an error message if option 2/3 is chosen before option 1
  • Your program will throw an Exception in the menu if the user decides to input anything but an int
  • You do not have a default max score of 200

2) Your dice class instantiates Random each time the dice is rolled. This is not how the Random class is intended to be used. Instead, hold a class variable of type Random in your Dice class and continue to use the instance in your roll of the dice.

3) Sounds like you might be expanding upon this game in the future. Consider holding your players in a data structure (like a List) now instead of listing them out. You can then iterate over the players in the List to do their rolls and check if anyone has won. This will necessarily change your checkIfAnyoneHasWon method, but it will make it easier for your next assignment.

4) You don't specify an access modifier for most of the methods in your Game class. Pick one that makes sense for each method. In its current state, I would suggest to just use private on all of them.