Ferdinand BATANA, DBA & Web Developer(OCAJP, MCSE SQL SERVER)
Les tableaux
Comme dans tout langage de programmation qui se respecte, Java
travaille aussi avec des tableaux Déclarer et initialiser un tableau
Déclaration d’un tableau
<type du tableau> <nom du tableau> [] = { <contenu du tableau>}; Un tableau d’entiers int tableauEntier[] = {0,1,2,3,4,5,6,7,8,9}; Un tableau de double double tableauDouble[] = {0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0}; Tableau de caractères char tableauCaractere[] = {'a','b','c','d','e','f','g'}; Tableau de chaine de caractères String tableauChaine[] = {"chaine1", "chaine2", "chaine3" , "chaine4"}; Déclarer un tableau vide
int tableauEntier[] = new int[6];
//ou encore int[] tableauEntier2 = new int[6]; Tableaux multi-dimensionnels
Ici, les choses se compliquent un peu. Car un tableau multi-
dimensionnel n'est rien d'autre qu'un tableau ayant comme contenu au minimum 2 tableaux.. int premiersNombres[][] = { {0,2,4,6,8},{1,3,5,7,9} }; Utiliser et rechercher dans un tableau !
Un tableau, comme ceux que nous avons fait ci-dessus, débute
toujours à l'indice 0 ! Pour afficher la première valeur du tableau ci-dessus: System.out.println(tableauCaractere[0]); char tableauCaractere[] = {'a','b','c','d','e','f','g'}; System.out.println(tableauCaractere[0]); System.out.println(tableauCaractere[1]); System.out.println(tableauCaractere[2]); System.out.println(tableauCaractere[3]); Utiliser et rechercher dans un tableau ! Nous avons un moyen plus simple d’afficher le contenu d’un tableau char tableauCaractere[] = {'a','b','c','d','e','f','g'}; int i = 0; while (i < 4) { System.out.println("A l'emplacement " + i +" du tableau nous avons = " +tableauCaractere[i]); i++; } Qaund on ne connait pas la taille du tableau: char tableauCaractere[] = {'a','b','c','d','e','f','g'}; for(int i = 0; i < 4; i++) { System.out.println("A l'emplacement " + i +" du tableau nous avons = " +tableauCaractere[i]); } Utiliser et rechercher dans un tableau ! Tableau multi-dimensionnel int premiersNombres[][] = { {0,2,4,6,8},{1,3,5,7,9} }; for(int i = 0; i < 5; i++) { for(int j = 0; j < 2; j++) { System.out.print(premiersNombres[j][i]); } }