Table des matières

Correction TP1

On suppose que toutes vos classes sont dans le même package : ici com.mco. A la fin du TP, vous aurez deux classes (donc deux fichiers) :

Pour exécuter ce programme chez vous :

Les classes

On montrera la classe Dice et son utilisation avec la méthode main de la classe Main.

Dice.java

package com.mco;

import java.util.Random;

public class Dice {
    private int position; // Méthode générée automatiquement
    private Random randomGenerator;

    public Dice(int positionInitiale) {
        position = positionInitiale;
        randomGenerator = new Random();
    }

    public Dice() {
        this(1);
    }

    public int getPosition() { // Méthode générée automatiquement
        return position;
    }

    public void setPosition(int position) { // Méthode générée automatiquement
        this.position = position;
    }

    public void roll() {
        position = randomGenerator.nextInt(6) + 1;
    }

    @Override
    public String toString() { // Méthode générée automatiquement
        return "Dice{" +
                "position=" + position +
                '}';
    }

    @Override
    public boolean equals(Object o) { // Méthode générée automatiquement
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Dice dice = (Dice) o;

        return getPosition() == dice.getPosition();

    }

    @Override
    public int hashCode() { // Méthode générée automatiquement
        return getPosition();
    }
}

Spécificités :

Main.java

package com.mco;

public class Main {

    static void testDice() {
        System.out.println("---- Basic Dice tests ----");

        Dice firstDice = new Dice();
        System.out.println(firstDice); // position=1
        firstDice.setPosition(5);
        System.out.println(firstDice); // position=5

        Dice secondDice = new Dice(firstDice.getPosition());
        System.out.println(firstDice == secondDice); // false
        System.out.println(firstDice.equals(secondDice)); // true
        firstDice.setPosition(2);
        System.out.println(firstDice.equals(secondDice)); // false
    }

    static void testRandom() {
        System.out.println("---- Random tests ----");


        final int NUMBER_TRIES = 100;

        int numberOf1 = 0;
        Dice dice = new Dice();

        for (int i=0; i < NUMBER_TRIES; i+=1 ) {
            dice.roll();

            if (dice.getPosition() == 1) {
                numberOf1 += 1;
            }
        }

        System.out.println("Number of 1: " + numberOf1 + "/" + NUMBER_TRIES);  // 100 / 6 ~= 17
        System.out.println("Probability: " + (float)numberOf1 / NUMBER_TRIES); // 1 / 6 ~= 1.167
    }
 
   public static void main(String[] args) {
        testDice();
        testRandom();
    }
}

Spécificités :