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
| public class DessinTriangle {
private final static char FILL = '-';
private final static char BORDER = '*';
private final static char BACKGROUND = 'x';
public static void triangle(int n) {
if ( n>0 ) {
triangle(n, 0);
}
}
private static void triangle(int n, int iteration) {
int nombreEspaceExterne = iteration + 1; // nombre d'espaces de chaque côté
int longueur = n * 2 + 1; // longueur de ligne
char[] ligne = new char[longueur];
if ( nombreEspaceExterne>0 ) {
Arrays.fill(ligne, 0, nombreEspaceExterne, BACKGROUND); // espaces à gauche
Arrays.fill(ligne, ligne.length-nombreEspaceExterne, ligne.length, BACKGROUND); // espaces à droite
}
final int bordureGauche = nombreEspaceExterne; // position bordure
final int bordureDroite = ligne.length - bordureGauche - 1; // position bordure
ligne[bordureGauche]=BORDER; // bordure gauche
ligne[bordureDroite]=BORDER; // bordure droite
if( bordureDroite>bordureGauche ) {
Arrays.fill(ligne, bordureGauche+1, bordureDroite, iteration==0?BORDER:FILL); // pas de remplissage pour la ligne de base, mais une bordure
}
System.out.println(new String(ligne));
iteration++;
if (iteration < n) {
triangle(n, iteration);
}
}
public static void main(String[] args) {
triangle(7);
}
} |
Partager