Depuis le début de la formation, on utilise naturellement le println pour afficher dans la console, cependant, il exixte une autre manière de réprésenter les informations avec plus de précision avec printf()
println
printf()
C’est une méthode qui permet de formater et d’afficher des chaînes de caractères de manière précise. Pour ceux et celles qui connaissent, elle s’inspire de la fonction printf du langage C.
printf
Syntaxe : System.out.printf("Format", arg1, arg2, ...);
System.out.printf("Format", arg1, arg2, ...);
Exemple du TP6 (code en fin de page) :
Les spécificateurs de format commencent par % et indiquent comment formater les arguments.
%
%d
int
42
%f
float
double
3.141593
%.2f
3.14
%s
String
Bonjour
%c
char
A
%b
boolean
true
%e
3.141593e+00
%x
2a
%,d
1,000
%,.2f
1,234.57
Un spécificateur de format suit la structure suivante : %[flags][width][.precision]specifier
%[flags][width][.precision]specifier
+
0
%10d
int nombre = 42; System.out.printf("nombre : %d%n", nombre); // Affiche : Nombre : 42
double pi = 3.14159265359; System.out.printf("Pi : %.2f%n", pi); // Affiche : Pi : 3.14
Ci-dessous, il y a une largeur de 10 qui est définie.
int valeur = 123; System.out.printf("valeur : %10d%n", valeur); // Valeur : 123
int grandNombre = 1000000; System.out.printf("grand nombre : %,d%n", grandNombre); // Grand nombre : 1,000,000
Le - permet d’aligner vers la gauche.
-
String nom = "Mathieu"; System.out.printf("Nom : %-10s%n", nom); // Nom : Mathieu (aligné à gauche)
String nom = "Joachim"; int age = 21; double taille = 1.77; System.out.printf("%s a %d ans et mesure %.2f m.%n", nom, age, taille); // Joachim a 21 ans et mesure 1.77 m.
%10s
<br>
→
+%d
+56
%05d
00042
,
(
(%d
(46)
public class ExemplePrintf { public static void main(String[] args) { String nom = "Agnès"; int age = 56; double salaire = 2500.75; double taux = 0.15; // Affichage formaté System.out.printf("Nom : %-10s%n", nom); System.out.printf("Age : %+d ans%n", age); System.out.printf("Salaire : %,.2f €%n", salaire); System.out.printf("Taux : %.1f%%%n", taux * 100); // Il faut écrire %% pour afficher % } }
Sortie :
Nom : Agnès Âge : +56 ans Salaire : 2,500.75 € Taux : 15.0%
String[] noms = {"Agnès", "Joachim", "Mathieu"}; int[] ages = {56, 21, 24}; System.out.println("┌─────────────┬─────┐"); System.out.println("│ Nom │ Âge │"); System.out.println("├─────────────┼─────┤"); for (int i = 0; i < noms.length; i++) { System.out.printf("│ %-11s │ %3d │%n", noms[i], ages[i]); } System.out.println("└─────────────┴─────┘");
┌─────────────┬─────┐ │ Nom │ Âge │ ├─────────────┼─────┤ │ Agnès │ 56 │ │ Joachim │ 21 │ │ Mathieu │ 24 │ └─────────────┴─────┘
import java.time.LocalDateTime; LocalDateTime maintenant = LocalDateTime.now(); System.out.printf("Date : %02d/%02d/%d%n", maintenant.getDayOfMonth(), maintenant.getMonthValue(), maintenant.getYear()); System.out.printf("Heure : %02d:%02d:%02d%n", maintenant.getHour(), maintenant.getMinute(), maintenant.getSecond());
Date : 18/03/2026 Heure : 14:30:45
System.out.println()
Utiliser printfdans l’un des TP (semaine 1) pour le menu ou une partie des résultats à afficher.
static void afficherChateaux() { System.out.println("\n╔═══════════════════════════════════════════════════════════╗"); System.out.println("║ CHÂTEAUX DISPONIBLES ║"); System.out.println("╚═══════════════════════════════════════════════════════════╝"); System.out.println(); if (chateaux.isEmpty()) { System.out.println("Aucun château disponible."); return; } System.out.println("┌────────────────────────────────┬────────────────────┬───────────────────────┐"); System.out.println("│ Nom du Château │ Places disponibles │ Prix par billet (€) │"); System.out.println("├────────────────────────────────┼────────────────────┼───────────────────────┤"); for (Chateau chateau : chateaux) { System.out.printf("│ %-30s │ %18d │ %21.2f │%n", chateau.getNom(), chateau.getPlacesDisponibles(), chateau.getPrix()); } System.out.println("└────────────────────────────────┴────────────────────┴───────────────────────┘"); System.out.printf("Total châteaux : %d%n", chateaux.size()); }