Dans le chapitre 7, nous avons vu qu'un bon de commande pouvait être modélisé
par plusieurs tableaux à une dimension (nom, prixUnitaire, quantite) et le nombre d'articles distincts (n).
Nous allons ici les regrouper en un seul type :
class BonCommande {
int n;
String[] nom;
double[] prixUnitaire;
int[] quantite;
}
Lorsqu'on déclare une variable bon de type BonCommande (BonCommande bon), on regroupe
en une seule variable :
-
le nombre d'articles noté bon.n
-
tous les noms d'articles : bon.nom[0], bon.nom[1] ... bon.nom[bon.n-1]
-
tous les prix unitaires : bon.prixUnitaire[0], bon.prixUnitaire[1] ... bon.prixUnitaire[bon.n-1]
-
toutes les quantités : bon.quantite[0], bon.quantite[1] ... bon.quantite[bon.n-1]
La lisibilité du programme est donc améliorée, en particulier pour la
fonction totalCommande qui n'a qu'un paramètre :
Programme principal |
Fonction totalCommande |
void main() {
// saisie des donnees
BonCommande bon;
bon.n = readInt("nombre d'articles :");
bon.nom = new String[n];
bon.prixUnitaire = new double[n];
bon.quantite = new int[n];
int i;
for(i=0; i<bon.n; i=i+1) {
bon.nom[i]=readString("nom:");
bon.prixUnitaire[i]=readDouble("prix:");
bon.quantite[i]=readInt("quantite:");
}
// calcul et affichage du total
double totalCom;
totalCom = totalCommande(bon);
print("le total de la commande vaut ");
println(totalCom);
}
|
double totalCommande(BonCommande bon) {
int i;
double total;
total = 0;
for(i=0; i<bon.n; i=i+1) {
total = total + bon.quantite[i] *
bon.prixUnitaire[i];
}
return total;
}
|