1.使用判断三个数的最大值来举例嵌套
// 用判断三个数的大小学习嵌套和级联
// 嵌套的判断
Scanner in =new Scanner(System.in);
int x,y,z;
x=in.nextInt();
y=in.nextInt();
z=in.nextInt();
int max;
if(x>y)
{
if(x>z)
{max=x;}
else
{max=z;}
}
else
{
if(y>z)
{max=y;}
else
{max=z;}
}
System.out.println("三个数中最大的为:"+max);
运行结果实例:
2.使用分段函数来举例级联
Scanner in=new Scanner(System.in);
double x=in.nextDouble();
double f;
if(x<0) {
f=-1;
}else if(x==0) {
f=0;
}else {
f=2*x;
}
System.out.println(f);
运行结果举例:
小编自己的出的结论:总的来说,嵌套是if-else各自的语句中又存在了--子if-else语句 ,else语句也总是与最上面的if语句匹配;
而级联与嵌套的区别就在于级联中if-else语句中---else语句在竖直位置上是对齐的,级联一般用在分段函数的表示中。
级联: If-else if
if(exp1) { st1;}
else if(exp2) {st2;}
else {st3;}
多个if-else语句组成的语句就是级联的if-else if。