初聊Java的if语句

    科技2022-07-13  126

    Java的条件语句

    语法

    if语句的语法如下:

    if(布尔表达式){ //如果布尔表达式正确为true将执行{}里的代码,否则执行 if 语句块后面的代码 }

    例如:

    public class Test { public static void main(String args[]){ int x = 50; if( x > 20 ){ System.out.print("这是 if 语句"); } } }

    以上编译运行的结果就是这是 if 语句

    if…else语句

    if…else语句的语法如下:

    if(布尔表达式){ //如果布尔表达式的值为true }else{ //如果布尔表达式的值为false }

    例如:

    public class Test { public static void main(String args[]){ int x = 50; if( x < 20 ){ System.out.print("这是 if 语句"); }else{ System.out.print("这是 else 语句"); } } }

    以上编译运行的结果就是这是 else 语句

    if…else if…else语句

    if 语句后面可以跟 else if…else 语句

    使用 if,else if,else 语句的时候,需要注意下面几点:if 语句至多有 1 个 else 语句,else 语句在所有的 else if 语句之后。if 语句可以有若干个 else if 语句,它们必须在 else 语句之前。一旦其中一个 else if 语句检测为 true,其他的 else if 以及 else 语句都将跳过执行。

    if…else语句的语法如下:

    if(布尔表达式 1){ //如果布尔表达式 1的值为true执行代码 }else if(布尔表达式 2){ //如果布尔表达式 2的值为true执行代码 }else if(布尔表达式 3){ //如果布尔表达式 3的值为true执行代码 }else { //如果以上布尔表达式都不为true执行代码 }

    例如:

    public class Test { public static void main(String args[]){ int x = 30; if(x == 10){ System.out.print("值为"+x); }else if(x == 20){ System.out.print("值为"+x); }else if(x == 30){ System.out.print("值为"+x); }else{ System.out.print("这是 else 语句"); } } }

    以上编译运行的结果就是值为30

    嵌套的if…else语句

    嵌套的 if…else 语法格式如下:

    if(布尔表达式 1){ //如果布尔表达式 1的值为true执行代码 if(布尔表达式 2){ //如果布尔表达式 2的值为true执行代码 } }

    例如:

    public class Test { public static void main(String args[]){ int x = 50; int y = 20; if(x == 50){ if(y == 20){ System.out.print("X = "+x+" and Y = "+y); } } } }

    以上编译运行的结果就是X = 50 and Y = 20

    Processed: 0.014, SQL: 8