Object-Oriented Programming with Java, part I – Exercise 80

This exercise implements a dice class that accepts a dice size (numberOfSides) and returns a random number for that dice.

My Code

Main

public class Main {

    public static void main(String[] args) {

        Dice dice = new Dice(6);

        int i = 0;
        while (i < 10) {
            System.out.println(dice.roll());
            i++;
        }

    }
}

Dice

import java.util.Random;

public class Dice {
    private Random random = new Random();
    private int numberOfSides;

    public Dice(int numberOfSides) {
        // Initialize here the number of sides
        this.numberOfSides = numberOfSides;
        random = new Random();
    }

    public int roll() {
        // create here a random number belongig to range 1-numberOfSided
        return random.nextInt(numberOfSides) +1;
    }
}

Model Code

Main

public class Main {

 

    public static void main(String[] args) {

 

        Dice dice = new Dice(6);

 

        int i = 0;

        while (i < 10) {

            System.out.println(dice.roll());

            i++;

        }

 

    }

}

Dice

import java.util.Random;

 

public class Dice {

    private Random random = new Random();

    private int numberOfSides;

 

    public Dice(int numberOfSides) {

        // Initialize here the number of sides

        this.numberOfSides = numberOfSides;

    }

 

    public int roll() {

        // create here a random number belongig to range 1-numberOfSided

        return this.random.nextInt(this.numberOfSides) + 1;

    }

}

Comments

Interestingly the model code leaves out random = new Random(); from the constructor. It is in there in the exercise though…..

Leave a comment