IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

avec Java Discussion :

Simulation d'un fast food


Sujet :

avec Java

  1. #1
    Nouveau membre du Club
    Homme Profil pro
    Ingénieur de recherche
    Inscrit en
    Décembre 2011
    Messages
    52
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Finistère (Bretagne)

    Informations professionnelles :
    Activité : Ingénieur de recherche
    Secteur : Aéronautique - Marine - Espace - Armement

    Informations forums :
    Inscription : Décembre 2011
    Messages : 52
    Points : 34
    Points
    34
    Par défaut Simulation d'un fast food
    /!\ POST#1 Mis à jour en continu pour le code /!\

    Bonjour à tous

    Je crée un nouveau fil qui sera plus approprié pour poser mes questions au fur et à mesure.

    Le but de mon projet est de parvenir à simuler, de manière simplifiée, le fonctionnement d'un fast food.

    Pour l'instant, grâce à l'aide de nombreux forumers (que je remercie) j'avance progressivement.

    Avancement du projet: [terminé] [en cours] [à faire]
    -Permettre la création de nouveaux ingrédients que l'on ajoute à un stock d'ingrédients (méthode createIngredients())
    -Permettre la création de nouveaux produits (simple et composé) que l'on ajoute à un objet qui recense les produits disponibles à la vente (méthode createProduits())
    -Afficher la constitution d'un Produit_compose (méthode DecrisProduitCompose())
    -Lors de la création d'un Produit_compose, il faut retirer les Ingredient utilisés pour cette création au stock d'ingrédients
    -Mettre en place la partie "commande par un client"

    -------------------------------------------------------------------

    Un ingrédient est caractérisé par le fait qu'il n'est pas disponible à la commande mais intervient dans la préparation d'un produit_compose.
    Ex*: tomate, steack, cornichon, ...
    Un produit est caractérisé par le fait qu'il est disponible à la commande par un client.
    Un produit_compose est un produit qui se compose de plusieurs Ingrédient.
    Ex*: hamburger, glace 3 boules, ...
    Un produit_simple est, comme son nom l'indique, un produit qui «*ne se compose que de lui-même*».
    Ex*: frite, ketchup, soda, …

    ---------------------------------------------------------------------

    Un petit diagramme UML pour vous montrer où j'en suis:



    Uploaded with ImageShack.us

    Petite description des classes/méthodes:


    Classe Ingredient*: Elle permet de créer de nouveaux ingrédients qui se caractérisent par leur nom et leur prix unitaire. On y trouve les méthodes get et set associées ainsi q'une méthode permettant la description d'un tel objet.


    Classe Ingredients*: Elle représente les ingrédients en stock. Ici, on utilise le pattern design Singleton pour s'assurer qu'elle ne pourra être instanciée qu'une seule fois pendant la durée de l'application. On y trouve la méthode createIngredients() qui va créer un certain nombre d'ingrédients identiques et les ajouter au stock d'ingrédients.

    Classe Produit*: Il s'agit d'une classe abstraite qui est la super-classe des deux classes suivantes et qui comporte les habituelles méthodes get et set pour le nom du produit et son prix.

    Classe Produit_compose*: C'est une sous-classe de Produit qui permet la création de nouveaux produits composés via une liste de Ingredient passée en paramètre. Elle comporte également une méthode DecrisProduitCompose() qui retourne une chaîne de caractère indiquant les Ingrédient qui composent le produit composé.

    Classe Produit_simple*: C'est une sous-classe de Produit qui permet la création de nouveaux produits simples.

    Classe ProduitEnVente*: Elle représente les produits disponibles à la vente. On utilise également ici le pattern design Singleton pour s'assurer que nous n'aurons à faire qu'à une seule instance. La méthode createProduits() permet de créer plusieurs Produit_simple ou Produit_compose et de les ajouter à la liste qui représente les produits disponibles à la vente.

    Classe Test*: C'est notre main*!

    Les classes:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    public class Ingredient {
     
        protected String nom_ingredient;
        protected double prix_unitaire;
     
        Ingredient(String nom_ingredient, double prix_unitaire, Ingredients stock){
            this.nom_ingredient=nom_ingredient;
            this.prix_unitaire=prix_unitaire;
     
        }
     
     
     
        public String getNom_ingredient(){
        	return this.nom_ingredient;
        }
        public void setNom_ingredient(String nom_ingredient){
        	this.nom_ingredient=nom_ingredient;
        }
        public double getPrix_unitaire(){
        	return this.prix_unitaire;
        }
        public void setPrix_unitaire(int prix_unitaire){
        	this.prix_unitaire=prix_unitaire;
        }
        public String DecrisIngredient(){
            return "L'ingrédient "+this.nom_ingredient+" est au prix unitaire de "+this.prix_unitaire+" €";
        }
     
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
     import java.util.Arrays;
    import java.util.List;
    import java.util.ArrayList;
     
    /**
     * Permet de créer de nouveaux ingrédients.
     */
    public final class Ingredients {
     
        /**
         * Singleton statique qui permet de ne référencer qu'une seule instance
         * de la classe Ingredients.
         */
        private static Ingredients ingredients ;
     
        /**
         * Liste de tous les ingrédients créés par l'intermédiaire de l'instance
         * unique d'ingrédients.
         */
        private static List<Ingredient> stockIngredient;
     
        /**
         * Constructeur privé interdisant son instanciation à l'extérieur de la classe.
         */
        private  Ingredients() {
            Ingredients.stockIngredient = new ArrayList<Ingredient>();
        }
     
        public static Ingredients getInstance(){
        	if (ingredients==null){
        		ingredients=new Ingredients();
        	}
        	return ingredients;
        }
     
        public static List<Ingredient> getStockIngredients(){
        	return stockIngredient;
        }
     
     
     
        /**
         * Crée une nouvelle liste d'ingrédients.
         * @param ingredientType nom des ingrédients
         * @param price prix des ingrédients créés
         * @param quantity nombre d'ingrédients à créer
         * @return liste de tous les ingrédients créés
         */
        public static List<Ingredient> createIngredients(String ingredientType, double price, int quantity) {
            List<Ingredient> newIngredients = new ArrayList<Ingredient>();
            for (int i = 0; i < quantity; i++) {
                newIngredients.add(new Ingredient(ingredientType, price, ingredients));            
            }
            System.out.println(quantity+" "+ ingredientType+" ont été ajoutés au stock");
            Ingredients.stockIngredient.addAll(newIngredients);
            return newIngredients;
        }
     
     
        /**
         * Prendre un(des) ingrédient(s) du stock et les supprimer.
         * @param nom_ingredient nom des ingrédients
         * @param quantity nombre d'ingrédients à prendre du stock
         * @return liste de tous les ingrédients pris du stock
         */
     
        public static List<Ingredient> PrendreIngredientFromStockAndDeleteFromStock(String nom_ingredient, int quantity ){
        	List<Ingredient> liste_ingredient_pris=new ArrayList<Ingredient>();
        	int j = 0;
        	for (Ingredient ingred : Ingredients.stockIngredient){
        		if ( nom_ingredient== ingred.getNom_ingredient() &&  j<quantity){
        			liste_ingredient_pris.add(ingred);
        			Ingredients.stockIngredient.remove(ingred);
        			j++;
        			}
        	}
     
        	return liste_ingredient_pris;
     
       }
     
        /**
         * Decrire le stock d'ingrédients
              */
     
        public static void DecrisStock(){
        	String comp="Le stock d'ingrédients se composent de:";
        	for (Ingredient ing : stockIngredient){
        		comp = comp +"\n"+"-"+ ing.getNom_ingredient();
        		}
        	System.out.println(comp);
     
        }
     
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    /**
     * Classe abstraite qui "définit" un produit.
     */
    public abstract class Produit {
     
    	/**
             * Variables d'instance.
             */
     
        protected String nom_produit;
        protected double prix_produit;
     
        /**
         * Constructeur
         */
     
        protected Produit(String nom_produit, double prix_produit, ProduitsEnVente stock) {
            if (stock == null) {
                throw new IllegalArgumentException("Le stock ne peut pas être nul!");
            }
            this.nom_produit=nom_produit;
            this.prix_produit=prix_produit;
        }
     
        /**
         * Retourne le nom d'un produit.
         * @return nom d'un produit
         */
     
       public String getNom_produit(){
        	return this.nom_produit;
        }
     
       /**
        * Modifie le nom d'un produit.
        * @param nom_produit nom du produit
        */
     
        public void setNom_produit(String nom_produit){
        	this.nom_produit=nom_produit;
        }
     
        /**
         * Retourne le prix d'un produit.
         * @return prix du produit
         */
     
        public double getPrix_produit(){
        	return this.prix_produit;
        }
     
        /**
         * Modifie le prix d'un produit.
         * @param prix_produit prix du produit
         */
     
        public void setPrix_produit(double prix_produit){
        	this.prix_produit=prix_produit;
        }
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    import java.util.Arrays;
    import java.util.List;
     
    /**
     * Classe qui définit un produit compose.
     */
     
    public class Produit_compose extends Produit {
     
    	/**
             * liste des ingrédients qui entrent dans la composition d'un produit compose.
             */
     
        protected List<Ingredient> liste_ingredient;
     
        /**
             * Constructeur
             */
     
        Produit_compose(String nom_produit, double prix_produit, ProduitsEnVente stock, Ingredient... liste_ingredient) {
            super(nom_produit, prix_produit, stock);
            this.liste_ingredient = Arrays.asList(liste_ingredient);
     
             }
     
        /**
         * Decris un produit compose.
         * @return description du produit compose
         */
     
            public String DecrisProduitCompose() {
        	String composition="";
        	   	 	for (Ingredient ing : this.liste_ingredient){
        	   	 		composition= composition + ing.getNom_ingredient()+"\n ";
        	}
        		return  composition;
     
     
     
        	}
     
        }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    public class Produit_simple extends Produit {
     
        public Produit_simple(String nom_produit, double prix_produit, ProduitsEnVente stock) {
            super(nom_produit, prix_produit, stock);
     
        }
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    import java.util.ArrayList;
    import java.util.List;
     
    /**
     * Référence et créée de nouveaux produits.
     */
    public final class ProduitsEnVente {
     
        /**
         * Singleton de ProduitsEnVente utilisé pour référencer de manière unique
         * les produits créés par le système.
         */
        private static ProduitsEnVente produits = new ProduitsEnVente();
     
        /**
         * Liste des produits créés par ProduitsEnVente.
         */
        private List<Produit> products;
     
        /**
         * Constructeur privé qui permet à la classe de ne pas pouvoir être
         * instanciée.
         */
        private ProduitsEnVente() {
            products = new ArrayList<Produit>();
        }
     
        /**
         * Crée une liste de nouveaux Produit_simple.
         * @param productName nom des produits à créer
         * @param price prix des produits
         * @param quantité nom de Produit_simple à créer
         */
        public static List<Produit_simple> createProduits(String productName, double price, int quantity) {
            List<Produit_simple> newProducts = new ArrayList<Produit_simple>();
            for (int i = 0; i < quantity; i++) {
                newProducts.add(new Produit_simple(productName, price, produits));
     
            }
            System.out.println(quantity+" "+productName+" sont dorénavant disponibles à la commande");
            produits.products.addAll(newProducts);
            return newProducts;
        }
     
        /**
         * Crée une liste de nouveaux Produit_simple.
         * @param productName nom des produits à créer
         * @param price prix des produits
         * @param quantite quantite du même produit compose à créer
         * @param ingredients liste des ingrédients necessaire à la préparation du produit compose
         * @return liste des nouveaux produits identiquement créés.
         */
        public static List<Produit_compose> createProduits(String productName, double price, int quantite, Ingredient... ingredients) {
        	// Creation d'un Produit temporaire qui sert simplement à appliquer la méthode DecrisProduitCompose (comme on peut le voir, 
        	//il n'est pas ajouté à newproducts)
            List<Produit_compose> newProducts = new ArrayList<Produit_compose>();
            Produit_compose temp = new Produit_compose(productName, price, produits, ingredients);
            for (int i = 0; i < quantite; i++) {
                newProducts.add(new Produit_compose(productName, price, produits, ingredients));
     
                }
     
     
     
            System.out.println(quantite+" "+productName+" ont été préparés en cuisine et sont disponible à la commande");
            //System.out.println("Un "+productName+" se compose de:\n"+ temp.DecrisProduitCompose());
            produits.products.addAll(newProducts);
            return newProducts;
     
     
        }
     
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    import java.util.Arrays;
    import java.util.List;
    import java.util.ArrayList;
     
    public class Test {
     
    	public static void main(String[] args)
    {
    	Ingredients.getInstance();
    		// On crée une liste composée de 4 tomates 
            List<Ingredient> tomates = Ingredients.createIngredients("tomate", 0.5, 4);
            // Description d'une tomate
            System.out.println(tomates.get(0).DecrisIngredient());
            // On rajoute 0 tomates 
            tomates.addAll(Ingredients.createIngredients("tomate", 0.5, 0));
            // On ajoute 4 steacks
            List<Ingredient> steacks = Ingredients.createIngredients("steack", 2, 2);
            System.out.println(steacks.get(0).DecrisIngredient());
            List<Ingredient> cornichons = Ingredients.createIngredients("cornichon", 0.2, 4);
            Ingredients.DecrisStock();
     
     
            // On crée une liste d'ingrédients nécessaires à la préparation d'un seul BigMac
            List<Ingredient> ingredients = new ArrayList<Ingredient>();
            //On y ajoute 2 tomates
            ingredients.addAll(Ingredients.PrendreIngredientFromStockAndDeleteFromStock( "tomate", 2 ));
            //... puis 1 steack...
            ingredients.addAll(Ingredients.PrendreIngredientFromStockAndDeleteFromStock( "steack", 1 ));
     
            Ingredients.DecrisStock();
     
            // On crée une liste d'ingrédients nécessaires à la préparation d'un CheeseBurger
            //List<Ingredient> ingredients2 = Ingredients.createIngredients("cornichon", .3, 2);
           // ingredients2.addAll(Ingredients.createIngredients("tomate", .5, 1));
            //ingredients2.addAll(Ingredients.createIngredients("steack", 1, 1));
            //ingredients2.addAll(Ingredients.createIngredients("cheddar", 1, 2));
            // On crée 5 BigMacs qui sont automatiquement ajoutés aux produits disponibles à la vente
            List<Produit_compose> BigMacs = ProduitsEnVente.createProduits("Big Mac", 4.5, 2, ingredients.toArray(new Ingredient[ingredients.size()]));
            //// On crée 3 CheeseBurgers qui sont automatiquement ajoutés aux produits disponibles à la vente
            //List<Produit_compose> CheeseBurgers = ProduitsEnVente.createProduits("Cheeseburger", 4.5, 3, ingredients2.toArray(new Ingredient[ingredients2.size()]));
            // On crée une liste de 12 frites qui sont automatiquement ajoutées aux produits disponibles à la vente
            List<Produit_simple> Frites = ProduitsEnVente.createProduits("frite", 4.5, 12);
            Ingredients.DecrisStock();
     
        }
     
    }

  2. #2
    Nouveau membre du Club
    Homme Profil pro
    Ingénieur de recherche
    Inscrit en
    Décembre 2011
    Messages
    52
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Finistère (Bretagne)

    Informations professionnelles :
    Activité : Ingénieur de recherche
    Secteur : Aéronautique - Marine - Espace - Armement

    Informations forums :
    Inscription : Décembre 2011
    Messages : 52
    Points : 34
    Points
    34
    Par défaut
    Je suis en train de coder quelque chose qui me permettrait de supprimer les Ingredient du stock d'ingrédients appelés lors de la création d'un Produit_compose.

    J'ai commencé par créer cette méthode dans la classe Ingredients
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
     
    public void RemoveIngredientsFromStock(Ingredient...ingredients_a_supprimer){
        		  	for ( Ingredient temp : ingredients_a_supprimer){
        		ingredients.stockIngredient.remove(temp);
        		}
     
        }
    ainsi que celle-ci:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     public Ingredients getIngredients(){
        	return ingredients;
        }
    Je tente ensuite ceci dans ma classe ProduitsEnVente:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    public static List<Produit_compose> createProduits(String productName, double price, int quantite, Ingredient... ingredients) {
        	// Creation d'un Produit temporaire qui sert simplement à appliquer la méthode DecrisProduitCompose (comme on peut le voir, 
        	//il n'est pas ajouté à newproducts)
            List<Produit_compose> newProducts = new ArrayList<Produit_compose>();
            Produit_compose temp = new Produit_compose(productName, price, produits, ingredients);
            for (int i = 0; i < quantite; i++) {
                newProducts.add(new Produit_compose(productName, price, produits, ingredients));
               Ingredients.getIngredients().RemoveIngredientFromStock(ingredients);
            }
            System.out.println(quantite+" "+productName+" ont été préparés en cuisine et sont disponible à la commande");
            System.out.println("Un "+productName+" se compose de:\n"+ temp.DecrisProduitCompose());
            produits.products.addAll(newProducts);
            return newProducts;
    En gros, avec le code en rouge, je veux que les Ingredient que l'on a utilisé pour composer un Produit_compose soient supprimés du stock d'ingrédients.
    Cependant, j'obtiens les erreurs suivantes:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    Cannot invoke getIngredients() on the array type Ingredient[]
     Cannot make a static reference to the non-static method getIngredients() from the type Ingredients
    Je pense que le problème viens du faites que j'arrive pas à accéder au Singleton Ingredients dans ma méthode CreateProduits()...

    Si quelqu'un voit l'erreur je suis preneur

  3. #3
    Nouveau membre du Club
    Homme Profil pro
    Ingénieur de recherche
    Inscrit en
    Décembre 2011
    Messages
    52
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Finistère (Bretagne)

    Informations professionnelles :
    Activité : Ingénieur de recherche
    Secteur : Aéronautique - Marine - Espace - Armement

    Informations forums :
    Inscription : Décembre 2011
    Messages : 52
    Points : 34
    Points
    34
    Par défaut
    J'ai tenté autre chose mais le résultat n'est pas au rendez-vous:

    Dans ma classe Ingredients:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    public List<Ingredient> getStockIngredients(){
        	return stockIngredient;
        }
    et dans la classe ProduitsEnVente:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
     public static List<Produit_compose> createProduits(String productName, double price, int quantite, Ingredient... ingredients) {
        	// Creation d'un Produit temporaire qui sert simplement à appliquer la méthode DecrisProduitCompose (comme on peut le voir, 
        	//il n'est pas ajouté à newproducts)
            List<Produit_compose> newProducts = new ArrayList<Produit_compose>();
            Produit_compose temp = new Produit_compose(productName, price, produits, ingredients);
            for (int i = 0; i < quantite; i++) {
                newProducts.add(new Produit_compose(productName, price, produits, ingredients));
                
                for (Ingredient tempo : ingredients){
                	Ingredients.getStockIngredients().remove(tempo);
                }
              
            }
            System.out.println(quantite+" "+productName+" ont été préparés en cuisine et sont disponible à la commande");
            System.out.println("Un "+productName+" se compose de:\n"+ temp.DecrisProduitCompose());
            produits.products.addAll(newProducts);
            return newProducts;
            
            
        }
    Contrairement à ma tentative précédente je n'utilise pas la méthode RemoveIngredientsFromStock().

    J'obtiens toujours la même erreur.
    Je vais bien finir par y arriver ^^

    EDIT: Encore une tentative comme ceci:

    Ajout de cette méthode dans la classe Ingredients:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    public String DecrisStock(){
        	String comp="";
        	for (Ingredient ing : stockIngredient){
        		comp = comp + ing.getNom_ingredient();
        		}
        	return comp;
     
        }
    Modification de la classe ProduitsEnVente comem suit:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    public static List<Produit_compose> createProduits(String productName, double price, int quantite, Ingredient... ingredients) {
        	// Creation d'un Produit temporaire qui sert simplement à appliquer la méthode DecrisProduitCompose (comme on peut le voir, 
        	//il n'est pas ajouté à newproducts)
            List<Produit_compose> newProducts = new ArrayList<Produit_compose>();
            Produit_compose temp = new Produit_compose(productName, price, produits, ingredients);
            for (int i = 0; i < quantite; i++) {
                newProducts.add(new Produit_compose(productName, price, produits, ingredients));
                
                for (Ingredient tempo : ingredients){
                	Ingredients.getStockIngredients().remove(tempo);
                }
              
            }
            System.out.println(quantite+" "+productName+" ont été préparés en cuisine et sont disponible à la commande");
            System.out.println("Un "+productName+" se compose de:\n"+ temp.DecrisProduitCompose());
            produits.products.addAll(newProducts);
            return newProducts;
            
            
        }
    Jusque là pas d'erreur mais dans mon main, lorsque j'écris:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
     // On crée une liste d'ingrédients nécessaires à la préparation d'un BigMac où l'on ajoute 2 cornichons...
            List<Ingredient> ingredients = Ingredients.createIngredients("cornichon", .3, 50);
            //... puis 1 tomate...
            ingredients.addAll(Ingredients.createIngredients("tomate", .5, 50));
            //... puis 1 steack...
            ingredients.addAll(Ingredients.createIngredients("steack", 1, 50));
            Ingredients.DecrisStock();
    J'obtiens Exception in thread "main" java.lang.Error: Unresolved compilation problem:
    The method DecrisStock() is undefined for the type List<Ingredient>

    at Test.main(Test.java:24)


    Toutes les solutions envisagées s'avèrent être un échec donc si une âme charitable peut m'aiguiller.

    Merci de votre aide!

  4. #4
    Nouveau membre du Club
    Homme Profil pro
    Ingénieur de recherche
    Inscrit en
    Décembre 2011
    Messages
    52
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Finistère (Bretagne)

    Informations professionnelles :
    Activité : Ingénieur de recherche
    Secteur : Aéronautique - Marine - Espace - Armement

    Informations forums :
    Inscription : Décembre 2011
    Messages : 52
    Points : 34
    Points
    34
    Par défaut
    En fait j'ai mélangé de trucs totalement différents dans le post précédent, le code:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     for (Ingredient tempo : ingredients){
                	Ingredients.getStockIngredients().remove(tempo);
                }
    dans la classe createProduits c'est pour supprimer les objets Ingredient du stock une fois qu'ils interviennent dans la conception d'un Produit_compose,

    Mais ce code là:
    Dans la classe Ingredients
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    public String DecrisStock(){
        	String comp="";
        	for (Ingredient ing : stockIngredient){
        		comp = comp + ing.getNom_ingredient();
        		}
        	return comp;
     
        }
    et dans le main:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    Ingredients.DecrisStock();
    Ca c'est pour pouvoir décrire le stock d'ingrédients mais le problème semble être le même à chaque fois, d'où ma question:
    Comment peut-on accéder aux variables d'instances d'un Singleton depuis une autre classe?

    Merci de votre aide

    EDIT: Je viens lire ceci:
    attentivement et je peux y lire
    Constructeur redéfini comme étant privé pour interdire
    * son appel et forcer à passer par la méthode <link
    mais qu'est ce que cette méthode link?

  5. #5
    Membre habitué
    Homme Profil pro
    Consultant informatique
    Inscrit en
    Novembre 2011
    Messages
    101
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Belgique

    Informations professionnelles :
    Activité : Consultant informatique
    Secteur : Distribution

    Informations forums :
    Inscription : Novembre 2011
    Messages : 101
    Points : 134
    Points
    134
    Par défaut
    Ta classe Ingredients contient le stock de tes ingrédients si je comprends bien.

    Elle n'est instanciée qu'une fois, et donc quand tu fais appel à cette classe tu as accès à tous tes ingrédients en stock.

    Le soucis est que pour pouvoir faire ceci :

    Ingredients.getIngredients().RemoveIngredientFromStock(ingredients);

    Il faut que la méthode getIngredients() soient statique.

    En fait, tous les attributs et toutes les méthodes doivent être statiques...
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
     
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
     
    /**
     * Permet de créer de nouveaux ingrédients.
     */
    public final class Ingredients {
     
        /**
         * Singleton statique qui permet de ne référencer qu'une seule instance
         * de la classe Ingredients.
         */
        private static Ingredients ingredients = new Ingredients();
     
        /**
         * Liste de tous les ingrédients créés par l'intermédiaire de l'instance
         * unique d'ingrédients.
         */
        private static List<Ingredient> stockIngredient;
     
        /**
         * Constructeur privé interdisant son instanciation à l'extérieur de la classe.
         */
        private static Ingredients() {
            this.stockIngredient = new ArrayList<Ingredient>();
        }
     
     
     
        /**
         * Crée une nouvelle liste d'ingrédients.
         * @param ingredientType nom des ingrédients
         * @param price prix des ingrédients créés
         * @param quantity nombre d'ingrédients à créer
         * @return liste de tous les ingrédients créés
         */
        public static List<Ingredient> createIngredients(String ingredientType, double price, int quantity) {
            List<Ingredient> newIngredients = new ArrayList<Ingredient>();
            for (int i = 0; i < quantity; i++) {
                newIngredients.add(new Ingredient(ingredientType, price, ingredients));            
            }
            System.out.println(quantity+" "+ ingredientType+" ont été ajoutés au stock");
            ingredients.stockIngredient.addAll(newIngredients);
            return newIngredients;
        }
     
        public static void RemoveIngredientsFromStock(Ingredient...ingredients_a_supprimer){
        		  	for ( Ingredient temp : ingredients_a_supprimer){
        		ingredients.stockIngredient.remove(temp);
        		}
     
        }
        public static Ingredients getIngredients(){
        	return ingredients;
        }
     
     
       }
    Voilà en tout cas pour ton erreur de départ. Après je n'ai pas suivi tout le code, ni l'optimisation de celui-ci. En orienté objet, il est plus simple d'instancier un objet de stock et de faire les opérations sur celui-ci... Enfin, j'espre que ça t'aidera à avancer.

  6. #6
    Nouveau membre du Club
    Homme Profil pro
    Ingénieur de recherche
    Inscrit en
    Décembre 2011
    Messages
    52
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Finistère (Bretagne)

    Informations professionnelles :
    Activité : Ingénieur de recherche
    Secteur : Aéronautique - Marine - Espace - Armement

    Informations forums :
    Inscription : Décembre 2011
    Messages : 52
    Points : 34
    Points
    34
    Par défaut
    Et bien j'ai un peu avancé jusqu'à maintenant. J'ai réussi à décrire mon stock d'ingrédients et à retirer les ingrédients du stock quand ils sont appelés pour la création d'un produit composé mais avec un petit soucis...
    Comme quelques lignes de code valent mieux qu'un long discours:

    Modification de la méthode createProduits dans la classe ProduitsEnVente comme suit:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    public static List<Produit_compose> createProduits(String productName, double price, int quantite, Ingredient... ingredients) {
        	// Creation d'un Produit temporaire qui sert simplement à appliquer la méthode DecrisProduitCompose (comme on peut le voir, 
        	//il n'est pas ajouté à newproducts)
            List<Produit_compose> newProducts = new ArrayList<Produit_compose>();
            Produit_compose temp = new Produit_compose(productName, price, produits, ingredients);
            for (int i = 0; i < quantite; i++) {
                newProducts.add(new Produit_compose(productName, price, produits, ingredients));
    // On supprime du stock les ingrédients appelés lors de la création d'un produit composé et ceci pour chaque produit composé!
                for (Ingredient tempo : ingredients){
                	Ingredients.getInstance();
    				Ingredients.getStockIngredients().remove(tempo);            	
                }
              }
            System.out.println(quantite+" "+productName+" ont été préparés en cuisine et sont disponible à la commande");
            //System.out.println("Un "+productName+" se compose de:\n"+ temp.DecrisProduitCompose());
            produits.products.addAll(newProducts);
            return newProducts;
            
            
        }
    Dans le main j'ai:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    import java.util.Arrays;
    import java.util.List;
    import java.util.ArrayList;
     
    public class Test {
     
    	public static void main(String[] args)
    {
    	Ingredients.getInstance();
    		// On crée une liste composée de 4 tomates 
            List<Ingredient> tomates = Ingredients.createIngredients("tomate", 0.5, 4);
            // Description d'une tomate
            System.out.println(tomates.get(0).DecrisIngredient());
            // On rajoute 0 tomates 
            tomates.addAll(Ingredients.createIngredients("tomate", 0.5, 0));
            // On ajoute 4 steacks
            List<Ingredient> steacks = Ingredients.createIngredients("steack", 2, 2);
            System.out.println(steacks.get(0).DecrisIngredient());
            List<Ingredient> cornichons = Ingredients.createIngredients("cornichon", 0.2, 4);
            Ingredients.DecrisStock();
     
     
            // On crée une liste d'ingrédients nécessaires à la préparation d'un seul BigMac où l'on ajoute 2 cornichons...
            List<Ingredient> ingredients = Ingredients.createIngredients("cornichon", .2, 2);
            //... puis 1 tomate...
            ingredients.addAll(Ingredients.createIngredients("tomate", .5, 1));
            //... puis 1 steack...
            ingredients.addAll(Ingredients.createIngredients("steack", 2, 1));
     
            Ingredients.DecrisStock();
     
            // On crée une liste d'ingrédients nécessaires à la préparation d'un CheeseBurger
            //List<Ingredient> ingredients2 = Ingredients.createIngredients("cornichon", .3, 2);
           // ingredients2.addAll(Ingredients.createIngredients("tomate", .5, 1));
            //ingredients2.addAll(Ingredients.createIngredients("steack", 1, 1));
            //ingredients2.addAll(Ingredients.createIngredients("cheddar", 1, 2));
            // On crée 5 BigMacs qui sont automatiquement ajoutés aux produits disponibles à la vente
            List<Produit_compose> BigMacs = ProduitsEnVente.createProduits("Big Mac", 4.5, 2, ingredients.toArray(new Ingredient[ingredients.size()]));
            //// On crée 3 CheeseBurgers qui sont automatiquement ajoutés aux produits disponibles à la vente
            //List<Produit_compose> CheeseBurgers = ProduitsEnVente.createProduits("Cheeseburger", 4.5, 3, ingredients2.toArray(new Ingredient[ingredients2.size()]));
            // On crée une liste de 12 frites qui sont automatiquement ajoutées aux produits disponibles à la vente
            List<Produit_simple> Frites = ProduitsEnVente.createProduits("frite", 4.5, 12);
            Ingredients.DecrisStock();
     
        }
     
    }
    qui me renvois:
    4 tomate ont été ajoutés au stock
    L'ingrédient tomate est au prix unitaire de 0.5 €
    0 tomate ont été ajoutés au stock
    2 steack ont été ajoutés au stock
    L'ingrédient steack est au prix unitaire de 2.0 €
    4 cornichon ont été ajoutés au stock
    Le stock d'ingrédients se composent de:
    -tomate
    -tomate
    -tomate
    -tomate
    -steack
    -steack
    -cornichon
    -cornichon
    -cornichon
    -cornichon
    2 cornichon ont été ajoutés au stock
    1 tomate ont été ajoutés au stock
    1 steack ont été ajoutés au stock
    Le stock d'ingrédients se composent de:
    -tomate
    -tomate
    -tomate
    -tomate
    -steack
    -steack
    -cornichon
    -cornichon
    -cornichon
    -cornichon
    -cornichon
    -cornichon
    -tomate
    -steack
    2 Big Mac ont été préparés en cuisine et sont disponible à la commande
    12 frite sont dorénavant disponibles à la commande
    Le stock d'ingrédients se composent de:
    -tomate
    -tomate
    -tomate
    -tomate
    -steack
    -steack
    -cornichon
    -cornichon
    -cornichon
    -cornichon
    Déjà un truc qu'il faudra modifier à l'avenir c'est que lorsque je constitue la liste d'ingrédients qui servira à créer mon produit_compose (liste "ingredients" dans le main) qu'elle ne crée pas de nouveaux objets mais qu'elle récupère ce dont elle a besoin dans le stock d'ingrédients.
    Mais pour l'instant, ce qui m'embête, hormis précédemment, c'est que lorsque je donne la composition d'un produit (bigmac en l'occurence) et que je lance la création de deux bigmac, les ingrédients ne sont supprimer qu'une seule fois (en gros le fait de créer 1 ou n produits composés n'impacte pas le stock d'ingrédients).
    En fait, on a bien 2 cornichons + 1 steak + 1 tomate qui disparaissent du stock d'ingredients mais c'est normal c'est les éléments de la liste "ingredients" donc logiquement, il devrait y avoir 2 cornichons + 1 steak + 1 tomate en moins dans le stock après la création du 2nd bigmac.

    Voilà pour les news!

    EDIT: Post#1 Mis à jour

  7. #7
    Nouveau membre du Club
    Homme Profil pro
    Ingénieur de recherche
    Inscrit en
    Décembre 2011
    Messages
    52
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Finistère (Bretagne)

    Informations professionnelles :
    Activité : Ingénieur de recherche
    Secteur : Aéronautique - Marine - Espace - Armement

    Informations forums :
    Inscription : Décembre 2011
    Messages : 52
    Points : 34
    Points
    34
    Par défaut
    /!\ Mise à jour POST#1 /!\


    Bonjour à tous!

    Alors j'ai tenté autre chose en ajoutant cette méthode:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    /**
         * Prendre un(des) ingrédient(s) du stock et les supprimer.
         * @param nom_ingredient nom des ingrédients
         * @param quantity nombre d'ingrédients à prendre du stock
         * @return liste de tous les ingrédients pris du stock
         */
     
        public static List<Ingredient> PrendreIngredientFromStockAndDeleteFromStock(String nom_ingredient, int quantity ){
        	List<Ingredient> liste_ingredient_pris=new ArrayList<Ingredient>();
        	int j = 0;
        	for (Ingredient ingred : Ingredients.stockIngredient){
        		if ( nom_ingredient== ingred.getNom_ingredient() &&  j<quantity){
        			liste_ingredient_pris.add(ingred);
        			Ingredients.stockIngredient.remove(ingred);
        			j++;
        			}
        	}
     
        	return liste_ingredient_pris;
     
       }
    et en modifiant mon main ainsi:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    // On crée une liste d'ingrédients nécessaires à la préparation d'un seul BigMac
            List<Ingredient> ingredients = new ArrayList<Ingredient>();
            //On y ajoute 2 tomates
            ingredients.addAll(Ingredients.PrendreIngredientFromStockAndDeleteFromStock( "tomate", 2 ));
            //... puis 1 steack...
            ingredients.addAll(Ingredients.PrendreIngredientFromStockAndDeleteFromStock( "steack", 1 ));
    Je fais donc d'une pierre 2 coups puisque je constitue ma liste d'ingrédients qui me servira pour créer mon produit composé à partir du stock et qu'il sont supprimés en même temps.
    Cependant, même si je n'ai aucune erreur dans aucune classe lorsque je lance l'application j'ai les erreurs suivantes:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    4 tomate ont été ajoutés au stock
    L'ingrédient tomate est au prix unitaire de 0.5 €
    0 tomate ont été ajoutés au stock
    2 steack ont été ajoutés au stock
    L'ingrédient steack est au prix unitaire de 2.0 €
    4 cornichon ont été ajoutés au stock
    Le stock d'ingrédients se composent de:
    -tomate
    -tomate
    -tomate
    -tomate
    -steack
    -steack
    -cornichon
    -cornichon
    -cornichon
    -cornichon
    Exception in thread "main" java.util.ConcurrentModificationException
    	at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
    	at java.util.ArrayList$Itr.next(Unknown Source)
    	at Ingredients.PrendreIngredientFromStockAndDeleteFromStock(Ingredients.java:71)
    	at Test.main(Test.java:26)
    Si quelqu'un voit ce qui cloche, je suis preneur de tout conseil

  8. #8
    Membre confirmé
    Homme Profil pro
    Inscrit en
    Juin 2011
    Messages
    445
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Juin 2011
    Messages : 445
    Points : 622
    Points
    622
    Par défaut
    Tu n'as pas le droit de modifier une liste dans un For-each. (Enfin tu as le droit, mais ça lève une Exception...)

    Vu que tu fais des suppressions, à mon avis, le plus simple est de parcourir la liste depuis la fin en utilisant un for classique :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    public static List<Ingredient> PrendreIngredientFromStockAndDeleteFromStock(String nom_ingredient, int quantity ){
     
        List<Ingredient> liste_ingredient_pris=new ArrayList<Ingredient>();
     
        int j=0;
        for(int i=Ingredients.stockIngredient.size-1;i>=0;i++) {
          Ingredient ingred =Ingredients.stockIngredient.get(i);
          if ( nom_ingredient== ingred.getNom_ingredient()){
            Ingredients.stockIngredient.remove(i);
            liste_ingredient_pris.add(ingred);
            j++;
            if(j==quantity) {
              return liste_ingredient_pris;
            }
          }      
        }
     
        // Not found or not enough !!!
        return ???;
     }

  9. #9
    Nouveau membre du Club
    Homme Profil pro
    Ingénieur de recherche
    Inscrit en
    Décembre 2011
    Messages
    52
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Finistère (Bretagne)

    Informations professionnelles :
    Activité : Ingénieur de recherche
    Secteur : Aéronautique - Marine - Espace - Armement

    Informations forums :
    Inscription : Décembre 2011
    Messages : 52
    Points : 34
    Points
    34
    Par défaut
    Merci de ta réponse! J'avais trouvé une méthode similaire

  10. #10
    Nouveau membre du Club
    Homme Profil pro
    Ingénieur de recherche
    Inscrit en
    Décembre 2011
    Messages
    52
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Finistère (Bretagne)

    Informations professionnelles :
    Activité : Ingénieur de recherche
    Secteur : Aéronautique - Marine - Espace - Armement

    Informations forums :
    Inscription : Décembre 2011
    Messages : 52
    Points : 34
    Points
    34
    Par défaut
    Allez c'est parti pour MàJ des classes:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    /**
     * Classe abstraite qui "définit" un produit.
     */
    public class Produit {
     
    	/**
             * Variables d'instance.
             */
     
        protected String nom_produit;
        protected double prix_produit;
     
        /**
         * Constructeur
         */
     
        protected Produit(String nom_produit, double prix_produit) {
             this.nom_produit=nom_produit;
            this.prix_produit=prix_produit;
        }
     
        protected Produit(){
     
        }
     
        /**
         * Retourne le nom d'un produit.
         * @return nom d'un produit
         */
     
       public String getNom_produit(){
        	return this.nom_produit;
        }
     
       /**
        * Modifie le nom d'un produit.
        * @param nom_produit nom du produit
        */
     
        public void setNom_produit(String nom_produit){
        	this.nom_produit=nom_produit;
        }
     
        /**
         * Retourne le prix d'un produit.
         * @return prix du produit
         */
     
        public double getPrix_produit(){
        	return this.prix_produit;
        }
     
        /**
         * Modifie le prix d'un produit.
         * @param prix_produit prix du produit
         */
     
        public void setPrix_produit(double prix_produit){
        	this.prix_produit=prix_produit;
        }
     
     
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    /**
     * Classe qui définit un produit simple.
     */
     
    public class Produit_simple extends Produit {
     
    	/**
             * Constructeur
             */
     
        public Produit_simple(String nom_produit, double prix_produit) {
            super(nom_produit, prix_produit);
     
        }
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    import java.util.Arrays;
    import java.util.List;
     
    /**
     * Classe qui définit un produit compose.
     */
     
    public class Produit_compose extends Produit {
     
    	/**
             * liste des ingrédients qui entrent dans la composition d'un produit compose.
             */
     
        protected List<Ingredient> liste_ingredient;
     
        /**
             * Constructeur
             */
     
        Produit_compose(String nom_produit, double prix_produit, List<Ingredient>liste_ingredient) {
            super(nom_produit, prix_produit);
            this.liste_ingredient = liste_ingredient;
     
             }
     
        /**
         * Decris un produit compose.
         * @return description du produit compose
         */
     
            public String DecrisProduitCompose() {
        	String composition="";
        	   	 	for (Ingredient ing : this.liste_ingredient){
        	   	 		composition= composition + ing.getNom_ingredient()+"\n ";
        	}
        		return  composition;
     
     
     
        	}
     
        }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    public class Ingredient {
     
    	/**
             * Variables d'instance.
             */
     
        protected String nom_ingredient;
        protected double prix_unitaire;
     
        /**
         * Constructeur
         */
     
        Ingredient(String nom_ingredient, double prix_unitaire){
            this.nom_ingredient=nom_ingredient;
            this.prix_unitaire=prix_unitaire;
     
        }
     
     
        /**
         * Retourne le nom d'un produit.
         * @return nom d'un produit
         */
     
        public String getNom_ingredient(){
        	return this.nom_ingredient;
        }
     
        /**
         * Modifie le nom d'un ingredient.
         * @param nom_ingredient nom de l'ingredient
         */
     
        public void setNom_ingredient(String nom_ingredient){
        	this.nom_ingredient=nom_ingredient;
        }
     
        /**
         * Retourne le prix d'un ingredient.
         * @return prix de l'ingredient 
         */
     
        public double getPrix_unitaire(){
        	return this.prix_unitaire;
        }
     
        /**
         * Modifie le prix d'un ingredient.
         * @param prix_unitaire prix de l'ingredient
         */
     
        public void setPrix_unitaire(int prix_unitaire){
        	this.prix_unitaire=prix_unitaire;
        }
     
        /**
         * Decris l'ingredient
         * @return description de l'ingredient
         */
     
        public String DecrisIngredient(){
            return "L'ingrédient "+this.nom_ingredient+" est au prix unitaire de "+this.prix_unitaire+" €";
        }
     
     
     
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    import java.util.Arrays;
    import java.util.List;
    import java.util.ArrayList;
     
    /**
     * Permet de créer de nouveaux ingrédients.
     */
    public final class Ingredients {
     
        /**
         * Singleton statique qui permet de ne référencer qu'une seule instance
         * de la classe Ingredients.
         */
        private static Ingredients ingredients ;
     
        /**
         * Liste de tous les ingrédients créés par l'intermédiaire de l'instance
         * unique d'ingrédients.
         */
        private static List<Ingredient> stockIngredient;
     
        /**
         * Constructeur privé interdisant son instanciation à l'extérieur de la classe.
         */
        private  Ingredients() {
            Ingredients.stockIngredient = new ArrayList<Ingredient>();
        }
     
        public static Ingredients getInstance(){
        	if (ingredients==null){
        		ingredients=new Ingredients();
        	}
        	return ingredients;
        }
     
     
     
        public static List<Ingredient> getStockIngredients(){
        	return stockIngredient;
        }
     
     
     
        /**
         * Crée une nouvelle liste d'ingrédients.
         * @param ingredientType nom des ingrédients
         * @param price prix des ingrédients créés
         * @param quantity nombre d'ingrédients à créer
         * @return liste de tous les ingrédients créés
         */
        public static List<Ingredient> createIngredients(String ingredientType, double price, int quantity) {
            List<Ingredient> newIngredients = new ArrayList<Ingredient>();
            for (int i = 0; i < quantity; i++) {
                newIngredients.add(new Ingredient(ingredientType, price));            
            }
            System.out.println(quantity+" "+ ingredientType+" ont été ajoutés au stock");
            Ingredients.stockIngredient.addAll(newIngredients);
            return newIngredients;
        }
     
     
        /**
         * Prendre un(des) ingrédient(s) du stock et les supprimer.
         * @param nom_ingredient nom des ingrédients
         * @param quantity nombre d'ingrédients à prendre du stock
         * @return liste de tous les ingrédients pris du stock
         */
     
        public static List<Ingredient> PrendreIngredientFromStockAndDeleteFromStock(String nom_ingredient, int quantity ){
        	List<Ingredient> liste_ingredient_pris=new ArrayList<Ingredient>();
        	int j = 0;
        	for (Ingredient ingred : Ingredients.stockIngredient){
        		if (nom_ingredient.equals(ingred.getNom_ingredient()) &&  j<quantity){
        			liste_ingredient_pris.add(ingred);
        			j++;
        	        }
        	}
        	if (j!=quantity){
        		int diff=quantity-j;
        		System.out.println("Il manque "+diff+" "+nom_ingredient+" pour pouvoir composé le produit désiré");
        	}
        	Ingredients.stockIngredient.removeAll(liste_ingredient_pris);
        	return liste_ingredient_pris;
     
       }
     
        /**
         * Decrire le stock d'ingrédients
              */
     
        public static void DecrisStock(){
        	String comp="Le stock d'ingrédients se composent de:";
        	for (Ingredient ing : stockIngredient){
        		comp = comp +"\n"+"-"+ ing.getNom_ingredient();
        		}
        	System.out.println(comp);
     
        }
     
     
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    import java.util.ArrayList;
    import java.util.List;
     
    /**
     * Référence et créée de nouveaux produits.
     */
    public final class ProduitsEnVente {
     
        /**
         * Singleton de ProduitsEnVente utilisé pour référencer de manière unique
         * les produits créés par le système.
         */
        private static ProduitsEnVente produits = new ProduitsEnVente();
     
        /**
         * Liste des produits créés par ProduitsEnVente.
         */
        private static List<Produit> products;
     
        /**
         * Constructeur privé qui permet à la classe de ne pas pouvoir être
         * instanciée.
         */
        private ProduitsEnVente() {
            products = new ArrayList<Produit>();
        }
     
        public static ProduitsEnVente getInstance(){
        	if (produits==null){
        		produits=new ProduitsEnVente();
        	}
        	return produits;
        }
     
        /**
         * Crée une liste de nouveaux Produit_simple.
         * @param productName nom des produits à créer
         * @param price prix des produits
         * @param quantité nom de Produit_simple à créer
         */
        public static List<Produit_simple> createProduits(String productName, double price, int quantity) {
            List<Produit_simple> newProducts = new ArrayList<Produit_simple>();
            for (int i = 0; i < quantity; i++) {
                newProducts.add(new Produit_simple(productName, price));
     
            }
            System.out.println(quantity+" "+productName+" sont dorénavant disponibles à la commande");
            produits.products.addAll(newProducts);
            return newProducts;
        }
     
        /**
         * Crée une liste de nouveaux Produit_simple.
         * @param productName nom des produits à créer
         * @param price prix des produits
         * @param quantite quantite du même produit compose à créer
         * @param ingredients liste des ingrédients necessaire à la préparation du produit compose
         * @return liste des nouveaux produits identiquement créés.
         */
        public static List<Produit_compose> createProduits(String productName, double price, int quantite, List<Ingredient>ingredients) {
        	// Creation d'un Produit temporaire qui sert simplement à appliquer la méthode DecrisProduitCompose (comme on peut le voir, 
        	//il n'est pas ajouté à newproducts)
            List<Produit_compose> newProducts = new ArrayList<Produit_compose>();
            Produit_compose temp = new Produit_compose(productName, price, ingredients);
             for (int i = 0; i < quantite; i++) {
                newProducts.add(new Produit_compose(productName, price, ingredients));
                Ingredients.getInstance();
                Ingredients.getStockIngredients().remove(ingredients);
     
                }
     
            System.out.println(quantite+" "+productName+" ont été préparés en cuisine et sont disponible à la commande");
            //System.out.println("Un "+productName+" se compose de:\n"+ temp.DecrisProduitCompose());
            produits.products.addAll(newProducts);
            return newProducts;
     
     
        }
     
        public static List<Produit> getProducts(){
        	return products;
     
        }
     
        public static void DecrisStock(){
        	String compo = "Le stock de produits est : ";
     
        	for (Produit prod : products){
        		compo = compo +" "+ prod.getNom_produit();
        	}
        	System.out.println(compo);
     
        }
        public static Produit RechercherProduit(String nom_produit){
        	Produit temp = new Produit();
        	temp = null;
        	   	for (Produit prod : products){
        		int i=0;
        		if (nom_produit==prod.getNom_produit() && i<1){
        			i++;
        			temp=prod;
        			}
           	}
        	   	if (temp != null) {
        	   		System.out.println("Le produit a été trouvé");
        	   		}
        	   	else { 
        	   		System.out.println("Le produit n'a pas été trouvé!!!");
        	   		}
        	   	return temp;
        }
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    import java.util.ArrayList;
    import java.util.List;
    public class Commande {
     
     
     
    	private List<Produit> produits_commandes;
     
    	public Commande() {
    		produits_commandes = new ArrayList<Produit>();
    	}
    	public List<Produit> CommanderProduits(String nom_client, List<String>produits) {
    		List<Produit> OrderedProducts = new ArrayList<Produit>();
    		int i=0;
    		for (String prod : produits){
    			i=0;
    			ProduitsEnVente.getInstance();
    			for (Produit prodbis : ProduitsEnVente.getProducts()){
     
    			if (prod==prodbis.getNom_produit() && i<1){
    				i++;
    				OrderedProducts.add(prodbis);
    			}
    			}
    						}
    		ProduitsEnVente.getInstance();
    		ProduitsEnVente.getProducts().removeAll(OrderedProducts);
    		String compo = new String();
    		for (Produit prod2 : OrderedProducts){
    			compo = compo +" "+prod2.getNom_produit();
    					}
     
    		System.out.println("Mr "+nom_client+" vient de passer une commande: : "+compo+"");
    		return OrderedProducts;
    	}
    }
    La partie IHM juste débutée:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    import java.awt.Color;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JButton;
    import javax.swing.Box;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
     
    	public class Fenetre extends JFrame {
     
    		public Fenetre() {
     
    			this.setTitle("Commande");
    			this.setSize(600, 400);
    			this.setLocationRelativeTo(null);
    			// Instanciation d'un objet JPanel
    			// pan sera le content de notre JFrame
    			this.setContentPane(new Panneau());
     
    			this.setBackground(Color.YELLOW);
    			Box b1 = Box.createHorizontalBox();
    			b1.add(new JButton("Ajouter au panier"));
    			b1.add(new JButton("Retirer du panier"));
     
    			Box b2 = Box.createHorizontalBox();
    			b2.add(new JButton("Payer!"));
     
    			Box b3 = Box.createVerticalBox();
    			b3.add(b1);
    			b3.add(b2);
     
    			this.getContentPane().add(b3);
    			this.setVisible(true);
    }
    		}
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    import java.awt.Font;
    import java.awt.Graphics;
    import javax.swing.JPanel;
    import java.awt.Color;
    import java.awt.Image;
    import java.io.File;
    import java.io.IOException;
    import javax.imageio.ImageIO;
     
     
    public class Panneau extends JPanel{
    	public void paintComponent(Graphics g){
    		try {
    			Image img = ImageIO.read(new File ("fastfood.jpg"));
    			g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);
    		}
    		catch (IOException e){
    			e.printStackTrace();
    		}
     
    		Font font = new Font("Courrier", Font.BOLD,25);
    		g.setFont(font);
    		g.setColor(Color.ORANGE);
    		g.drawString("Bienvenue sur F.F.F : Fast Food...and Fat", 10, 20);
     
     
    	}
     
    }
    et le test unitaire:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    import java.util.Arrays;
    import java.util.List;
    import java.util.ArrayList;
     
     
    public class Test {
     
    	public static void main(String[] args) {
               Fenetre fen = new Fenetre();
    			Ingredients.getInstance();
    			ProduitsEnVente.getInstance();
     
    		// On crée une liste composée de 4 tomates 
            List<Ingredient> tomates = Ingredients.createIngredients("tomate", 0.5, 4);
            // Description d'une tomate
            System.out.println(tomates.get(0).DecrisIngredient());
            // On rajoute 0 tomates 
            tomates.addAll(Ingredients.createIngredients("tomate", 0.5, 0));
            // On ajoute 4 steacks
            List<Ingredient> steacks = Ingredients.createIngredients("steack", 2, 2);
            System.out.println(steacks.get(0).DecrisIngredient());
            List<Ingredient> cornichons = Ingredients.createIngredients("cornichon", 0.2, 6);
            Ingredients.DecrisStock();
     
     
            // On crée une liste d'ingrédients nécessaires à la préparation d'un seul BigMac
            List<Ingredient> ingredients = new ArrayList<Ingredient>();
            //On y ajoute 2 tomates
            ingredients.addAll(Ingredients.PrendreIngredientFromStockAndDeleteFromStock( "tomate", 2 ));
            //... puis 1 steack...
            ingredients.addAll(Ingredients.PrendreIngredientFromStockAndDeleteFromStock( "steack", 1 ));
            ingredients.addAll(Ingredients.PrendreIngredientFromStockAndDeleteFromStock( "cornichon", 4 ));
            Ingredients.DecrisStock();
     
            // On crée une liste d'ingrédients nécessaires à la préparation d'un CheeseBurger
            //List<Ingredient> ingredients2 = Ingredients.createIngredients("cornichon", .3, 2);
           // ingredients2.addAll(Ingredients.createIngredients("tomate", .5, 1));
            //ingredients2.addAll(Ingredients.createIngredients("steack", 1, 1));
            //ingredients2.addAll(Ingredients.createIngredients("cheddar", 1, 2));
            // On crée 5 BigMacs qui sont automatiquement ajoutés aux produits disponibles à la vente
            List<Produit_compose> BigMacs = ProduitsEnVente.createProduits("Big Mac", 4.5, 3, ingredients);
            //// On crée 3 CheeseBurgers qui sont automatiquement ajoutés aux produits disponibles à la vente
            //List<Produit_compose> CheeseBurgers = ProduitsEnVente.createProduits("Cheeseburger", 4.5, 3, ingredients2.toArray(new Ingredient[ingredients2.size()]));
            // On crée une liste de 12 frites qui sont automatiquement ajoutées aux produits disponibles à la vente
            List<Produit_simple> Frites = ProduitsEnVente.createProduits("frite", 4.5, 12);
          //  Ingredients.DecrisStock();
            ProduitsEnVente.getInstance();
            ProduitsEnVente.DecrisStock();
            List<String> produits = new ArrayList<String>();
     
            produits.add("frite");
            produits.add("Big Mac");
            produits.add("frite");
     
            Commande com1 = new Commande();
            com1.CommanderProduits("Albert", produits);
            ProduitsEnVente.getInstance();
            ProduitsEnVente.DecrisStock();
     
        }
     
    }
    Je vous mets le résultat:

    4 tomate ont été ajoutés au stock
    L'ingrédient tomate est au prix unitaire de 0.5 €
    0 tomate ont été ajoutés au stock
    2 steack ont été ajoutés au stock
    L'ingrédient steack est au prix unitaire de 2.0 €
    6 cornichon ont été ajoutés au stock
    Le stock d'ingrédients se composent de:
    -tomate
    -tomate
    -tomate
    -tomate
    -steack
    -steack
    -cornichon
    -cornichon
    -cornichon
    -cornichon
    -cornichon
    -cornichon
    Le stock d'ingrédients se composent de:
    -tomate
    -tomate
    -steack
    -cornichon
    -cornichon
    3 Big Mac ont été préparés en cuisine et sont disponible à la commande
    12 frite sont dorénavant disponibles à la commande
    Le stock de produits est : Big Mac Big Mac Big Mac frite frite frite frite frite frite frite frite frite frite frite frite
    Mr Florian vient de passer une commande: : frite Big Mac frite
    Le stock de produits est : Big Mac Big Mac frite frite frite frite frite frite frite frite frite frite frite
    Alors mon problème vient de la méthode CommanderProduits(). En effet, quand je lui demande de commander 2 produits différents (par exemple frite et Big Mac) il n'y a pas de soucis. En revanche comme on peut voir dans Test, Lorsque je commande 1 frite + 1 frite + 1 Big Mac, les trois produits sont ajoutés à ma commande, mais seuls 1 frite et 1 Big Mac sont retirés du stock de produit. Le problème vient peut-être du fait que 2 objets frite ont le même nom, mais je vois pas comment y remédier.
    Si quelqu'un a remarqué une subtilité que je n'aurai pas vu merci de me le signaler

Discussions similaires

  1. Probleme Voyageur de Commerce - Recuit Simulé
    Par dinver dans le forum Algorithmes et structures de données
    Réponses: 4
    Dernier message: 21/06/2009, 22h26
  2. Simuler un coup de molette sur un memo...
    Par dynobremo dans le forum Composants VCL
    Réponses: 2
    Dernier message: 28/02/2003, 11h31
  3. Simulation de transmission de paquet entre différent réseaux
    Par MelloW dans le forum Développement
    Réponses: 2
    Dernier message: 12/07/2002, 19h51
  4. FFT(Fast Fourier Transform)
    Par IngBen dans le forum Traitement du signal
    Réponses: 6
    Dernier message: 23/05/2002, 16h35

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo