If,If..else Java语句及其示例

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");			
	}
   }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

木合塔尔 麦麦提

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值