If,If..else Java语句及其示例
当我们需要基于条件执行一组语句时,我们需要使用控制流语句。例如,如果一个数字大于零,则我们希望打印“正数”,但如果它小于零,则希望打印“负数”。在这种情况下,我们在程序中有两个打印语句,但根据输入值,一次只执行一个打印语句。我们将看到如何使用控制语句在java程序中编写此类条件。
在本教程中,我们将看到四种类型的控制语句,您可以根据需求在java程序中使用:在本教程中将介绍以下条件语句:
a) if语句
b) 嵌套if语句
c) if-else语句
d) if-else-if语句
If语句
If语句由一个条件组成,后面跟着一个语句或一组语句,如下所示:
if(condition){ Statement(s); }
只有当给定条件为true时,语句才会被执行。如果条件为false,则完全忽略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");
}
}
}
嵌套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");
}
}
}
}
实例 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");
}
}
}
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);
}
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");
}
}
}