控制流程系列教材 (一)- Java的If 条件语句
条件判断
步骤1:if
步骤2:多表达式与一个表达式
步骤3:if 使用过程中可能遇到的坑
步骤4:if else
步骤5:else if
步骤6:练习-BMI
步骤7:答案-BMI
步骤8:练习-闰年
步骤9:答案-闰年
示例 1 : if
如果表达式1的值是true,
就执行表达式2
![if](https://i-blog.csdnimg.cn/blog_migrate/71f410e4fe4149bd633827cd9f2a80e1.png)
public class HelloWorld { public static void main(String[] args) { boolean b = true ; //如果成立就打印yes if (b){ System.out.println( "yes" ); } } } |
示例 2 : 多表达式与一个表达式
public class HelloWorld { public static void main(String[] args) { boolean b = false ; //如果有多个表达式,必须用大括弧包括起来 if (b){ System.out.println( "yes1" ); System.out.println( "yes2" ); System.out.println( "yes3" ); } //否则表达式2 3 无论b是否为true都会执行 if (b) System.out.println( "yes1" ); System.out.println( "yes2" ); System.out.println( "yes3" ); //如果只有一个表达式可以不用写括弧,看上去会简约一些 if (b){ System.out.println( "yes1" ); } if (b) System.out.println( "yes1" ); } } |
示例 3 : if 使用过程中可能遇到的坑
在第6行,if后面有一个分号; 而分号也是一个完整的表达式
如果b为true,会执行这个分号,然后打印yes
如果b为false,不会执行这个分号,然后打印yes
这样,看上去无论如何都会打印yes
public class HelloWorld { public static void main(String[] args) { boolean b = false ; if (b); System.out.println( "yes" ); } } |
示例 4 : if else
else 代表不成立的情况
![if else](https://i-blog.csdnimg.cn/blog_migrate/756a4602158085caa96d5c500b709fc8.png)
public class HelloWorld { public static void main(String[] args) { boolean b = false ; if (b) System.out.println( "yes" ); else System.out.println( "no" ); } } |
示例 5 : else if
else if 是多条件判断
public class HelloWorld { public static void main(String[] args) { //如果只使用 if,会执行4次判断 int i = 2 ; if (i== 1 ) System.out.println( 1 ); if (i== 2 ) System.out.println( 2 ); if (i== 3 ) System.out.println( 3 ); if (i== 4 ) System.out.println( 4 ); //如果使用else if, 一旦在18行,判断成立, 20行和22行的判断就不会执行了,节约了运算资源 if (i== 1 ) System.out.println( 1 ); else if (i== 2 ) System.out.println( 2 ); else if (i== 3 ) System.out.println( 3 ); else if (i== 4 ) System.out.println( 4 ); } } |
更多内容,点击了解: https://how2j.cn/k/control-flow/control-flow-if/271.html