Compter le nombre d’occurrence dans un tableau | java

Dans ce tutoriel nous allons découvrir comment compter le nombre d’occurrence dans un tableau en Java.
 
 

Exemple:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
public class Main {
public static void main(String[] args) {
int [] tab = new int [] {1, 1, 7, 3, 2, 2, 2, 4, 1};
int [] count = new int[100];
/* i : compteur, tmp : stock tmporairement la valeur
à un certain index du tableau tab[]*/
int i,tmp = 0;
/* tmp agira comme une valeur d'index pour le tableau count
et gardera une trace du nombre d'occurrences de chaque nombre*/
for(i = 0; i < tab.length; i++){
tmp = tab[i];
count[tmp]++;
}
for(i=1; i < count.length; i++){
if(count[i] > 0 && count[i] == 1){
System.out.printf("%d se produit %d fois\n",i, count[i]);
}
else if(count[i] >= 2){
System.out.printf("%d se produit %d fois\n",i, count[i]);
}
}
}
}
public class Main { public static void main(String[] args) { int [] tab = new int [] {1, 1, 7, 3, 2, 2, 2, 4, 1}; int [] count = new int[100]; /* i : compteur, tmp : stock tmporairement la valeur à un certain index du tableau tab[]*/ int i,tmp = 0; /* tmp agira comme une valeur d'index pour le tableau count et gardera une trace du nombre d'occurrences de chaque nombre*/ for(i = 0; i < tab.length; i++){ tmp = tab[i]; count[tmp]++; } for(i=1; i < count.length; i++){ if(count[i] > 0 && count[i] == 1){ System.out.printf("%d se produit %d fois\n",i, count[i]); } else if(count[i] >= 2){ System.out.printf("%d se produit %d fois\n",i, count[i]); } } } }
public class Main {
    public static void main(String[] args) {
        int [] tab = new int [] {1, 1, 7, 3, 2, 2, 2, 4, 1};
        int [] count = new int[100];
        /* i : compteur, tmp : stock tmporairement la valeur 
        à un certain index du tableau tab[]*/
        int i,tmp = 0;

        /* tmp agira comme une valeur d'index pour le tableau count 
        et gardera une trace du nombre d'occurrences de chaque nombre*/
        for(i = 0; i < tab.length; i++){
                tmp = tab[i];
                count[tmp]++;
        }

        for(i=1; i < count.length; i++){
            if(count[i] > 0 && count[i] == 1){
             System.out.printf("%d se produit %d fois\n",i, count[i]);
             }
            else if(count[i] >= 2){
                System.out.printf("%d se produit %d fois\n",i, count[i]);
            }

         }
    }
}

 
Sortie:

1 se produit 3 fois
2 se produit 3 fois
3 se produit 1 fois
4 se produit 1 fois
7 se produit 1 fois

 

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *