Cette nouvelle version traite le problème qui se pose quand le tableau
est entièrement utilisé, c'est à dire qu'il y a autant de produits que
de cases dans le tableau. Cela ne pose un problème que si on veut
ajouter un nouveau produit (méthode referencer
). Nous ne
traitons pas ce problème avec une exception car il est facile de
trouver une solution, à savoir prendre un tableau plus grand.
class Bizarre extends Exception{ String msg; Bizarre(String s){ msg = s; } void print(){ System.out.println(msg); } } class Product{ String nom; int ref; int qte; void print(){ System.out.print(nom+" "+ref+" "+qte); } Product(String n, int r, int q){ nom = n; ref = r; qte = q; } Product stocker(int delta)throws Bizarre{ if (delta < 0) throw new Bizarre("stocker: parametre negatif"); qte = qte + delta; return this; } Product destocker(int delta)throws Bizarre{ if (delta < 0) throw new Bizarre("destocker: parametre negatif"); if (delta > qte) throw new Bizarre("destocker: stock insuffisant"); qte = qte - delta; return this; } } class Stock{ Product[] t = new Product[10]; int nb = 0; protected int rechercher(int r){ for (int i=0; i < nb; i++){ if (t[i].ref == r) return i; } return -1; } Stock referencer(String n, int r) throws Bizarre{ if (rechercher(r)>-1) throw new Bizarre("referencer: cette reference existe: " + r); if (nb == t.length){ Product[] plusGrand = new Product[nb+10]; for (int i = 0; i < nb; i++){ plusGrand[i]=t[i]; } t = plusGrand; System.out.println("---- agrandissement du tableau, nb=" + nb); } t[nb] = new Product(n,r,0); nb = nb + 1; // nb++; return this; } Stock dereferencer(int r) throws Bizarre{ int indice = rechercher(r); if (indice == -1) throw new Bizarre("dereferencer: cette reference n'existe: pas " + r); t[indice] = t[nb-1]; nb = nb - 1; return this; } Stock ajouter(int r, int delta) throws Bizarre{ int indice = rechercher(r); if (indice == -1) throw new Bizarre("ajouter: cette reference n'existe: pas " + r); t[indice].stocker(delta); return this; } Stock retirer(int r, int delta) throws Bizarre{ int indice = rechercher(r); if (indice == -1) throw new Bizarre("retirer: cette reference n'existe: pas " + r); t[indice].destocker(delta); return this; } void etat(){ for (int i = 0; i<nb; i++){ t[i].print(); System.out.println(); } } } class Produit3{ public static void main(String[] arg){ Stock st = new Stock(); try{ for (int i = 0; i < 25; i++){ st.referencer("produit_" + i, 1000+i); } st.etat(); }catch (Bizarre biz){ System.out.println("Une erreur en survenue: "); biz.print(); System.out.println(); } } }