English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Dans ce programme, vous apprendrez à utiliser les boucles while et for en Java pour calculer le nombre de chiffres.
public class NumberDigits { public static void main(String[] args) { int count = 0, num = 3452; while(num != 0) { // num = num/10 num /= 10; ++count; } System.out.println("Number of digits: " + count); } }
When running this program, the output is:
Number of digits: 4
Dans ce programme, le boucle while continuera jusqu'à ce que l'expression de test num != 0 donne une valeur de 0 (false).
Après la première itération, num sera divisé par10Ses valeurs seront345Ensuite, count sera incrémenté de1.
Après la deuxième itération, la valeur de num sera34, and count will be incremented to2.
Après la troisième itération, la valeur de num sera3, and count will be incremented to3.
After the fourth iteration, the value of num will be 0, and count will be incremented to4.
Then evaluate the test expression as false and terminate the loop.
public class NumberDigits { public static void main(String[] args) { int count = 0, num = 123456; for(; num != 0; num/=10, ++count) { } System.out.println("Number of digits: " + count); } }
When running this program, the output is:
Number of digits: 6
In this program, instead of using a while loop, an empty for loop is used.
In each iteration, the value of num is divided by10, then count increases1.
If num != 0 is false, i.e., num = 0, the for loop exits.
Since the for loop has no body, it can be changed to a single statement in Java as follows:
for(; num != 0; num/=10, ++count);