English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Dans ce programme, vous apprendrez à utiliser les instructions if else et les instructions if..else imbriquées dans Java pour trouver le plus grand nombre dans trois nombres.
public class Largest { public static void main(String[] args) { double n1 = -4.5, n2 = 3.9, n3 = 2.5; if( n1 >= n2 && n1 >= n3) System.out.println(n1 + "Is the largest number."); else if (n2 >= n1 && n2 >= n3) System.out.println(n2 + "Is the largest number."); else System.out.println(n3 + "Is the largest number."); } }
When running the program, the output is:
3.9 is the largest number.
-4.5,3.9et2.5stored separately in the variables n1, n2and n3.
Then, to find the largest number, use the if...else statement to check the following conditions
if n1is greater than or equal to n2and n3, n1is the largest.
if n2is greater than or equal to n1and n3, n2is the largest.
otherwise, n3is the largest.
You can also use nested if..else statements to find the largest number.
public class Largest { public static void main(String[] args) { double n1 = -4.5, n2 = 3.9, n3 = 5.5; if(n1 >= n2) { if(n1 >= n3) System.out.println(n1 + "Is the largest number."); else System.out.println(n3 + "Is the largest number."); } else { if(n2 >= n3) System.out.println(n2 + "Is the largest number."); else System.out.println(n3 + "Is the largest number."); } } }
When running the program, the output is:
5.5 is the largest number.
In the above program, we are not checking two conditions in a single if statement, but using nested if to find the maximum condition.
Then, to find the largest number, use the if else statement to check the following conditions
if n1is greater than or equal to n2,
if n1is greater than or equal to n3, n1is the largest.
otherwise, n3is the largest.
other cases,
if n2is greater than or equal to both n3, n2is the largest.
otherwise, n3is the largest.