原文: https://beginnersbook.com/2017/08/if-else-statement-in-java/
当我们需要根据条件执行一组语句时,我们需要使用控制流语句。例如,如果一个数字大于零,那么我们要打印“正数”,但如果它小于零,那么我们要打印“负数”。在这种情况下,程序中有两个print语句,但根据输入值一次只执行一个print语句。我们将看到如何使用控制语句在 java 程序中编写这种类型的条件。
在本教程中,我们将看到四种类型的控制语句,您可以根据需求在 java 程序中使用:在本教程中,我们将介绍以下条件语句:
a)if语句
b)嵌套if语句
c)if-else语句
d)if-else-if语句
if语句
if语句包含条件,后跟语句或一组语句,如下所示:
if(condition){Statement(s);}
只有在给定条件为真时才会执行语句。如果条件为false,那么if语句体内的语句将被完全忽略。

if语句的示例
public class IfStatementExample {public static void main(String args[]){int num=70;if( num < 100 ){/* This println statement will only execute,* if the above condition is true*/System.out.println("number is less than 100");}}}
输出:
number is less than 100
Java 中的嵌套if语句
当在另一个if语句中有if语句时,它被称为嵌套if语句。
嵌套的结构如下所示:
if(condition_1) {Statement1(s);if(condition_2) {Statement2(s);}}
如果condition_1为true,则执行Statement1。只有条件(condition_1和condition_2)都为真时,Statement2才会执行。
嵌套if语句的示例
public class NestedIfExample {public static void main(String args[]){int num=70;if( num < 100 ){System.out.println("number is less than 100");if(num > 50){System.out.println("number is greater than 50");}}}}
输出:
number is less than 100number is greater than 50
在 Java 中使用if-else语句
这是if-else语句的外观:
if(condition) {Statement(s);}else {Statement(s);}
如果条件为真,则if内的语句将执行,如果条件为假,则else内的语句将执行。

if-else语句的示例
public class IfElseExample {public static void main(String args[]){int num=120;if( num < 50 ){System.out.println("num is less than 50");}else {System.out.println("num is greater than or equal 50");}}}
输出:
num is greater than or equal 50
if-else-if语句
当我们需要检查多个条件时使用if-else-if语句。在这个声明中,我们只有一个if和一个else,但是我们可以有多个else if。它也被称为if else if梯子。这是它的样子:
if(condition_1) {/*if condition_1 is true execute this*/statement(s);}else if(condition_2) {/* execute this if condition_1 is not met and* condition_2 is met*/statement(s);}else if(condition_3) {/* execute this if condition_1 & condition_2 are* not met and condition_3 is met*/statement(s);}...else {/* if none of the condition is true* then these statements gets executed*/statement(s);}
注意:这里要注意的最重要的一点是,在if-else-if语句中,只要满足条件,就会执行相应的语句集,忽略其余。如果没有满足条件,则执行else内的语句。
if-else-if的示例
public class IfElseIfExample {public static void main(String args[]){int num=1234;if(num <100 && num>=1) {System.out.println("Its a two digit number");}else if(num <1000 && num>=100) {System.out.println("Its a three digit number");}else if(num <10000 && num>=1000) {System.out.println("Its a four digit number");}else if(num <100000 && num>=10000) {System.out.println("Its a five digit number");}else {System.out.println("number is not between 1 & 99999");}}}
输出:
Its a four digit number
查看这些相关的 java 示例:
