嵌套的if是一个if语句,它是另一个if或else的目标。嵌套if语句表示if语句中的if语句。是的,Java允许我们在if语句中嵌套if语句。即,我们可以在另一个if语句中放置一个if语句。
句法:
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}

例:
// Java program to illustrate nested-if statement
class NestedIfDemo
{
public static void main(String args[])
{
int i = 10;
if (i == 10)
{
// First if statement
if (i < 15)
System.out.println("i is smaller than 15");
// Nested - if statement
// Will only be executed if statement above
// it is true
if (i < 12)
System.out.println("i is smaller than 12 too");
else
System.out.println("i is greater than 15");
}
}
}
输出:
i is smaller than 15 i is smaller than 12 too