Java If Else 语句

在 Java 中,if 语句用于测试条件。条件匹配它返回 true 的语句,否则它返回 false。

例如,如果我们想创建一个程序来测试正整数,那么我们必须测试整数是否大于零。

在这种情况下,if 语句很有帮助。

Java 中有四种类型的 if 语句:

  1. if 语句
  2. if-else 语句
  3. if-else-if 阶梯
  4. 嵌套 if 语句

if 语句

if 语句是单个基于条件的语句,仅在提供的条件为真时执行。

If 语句语法:


if(condition)
{  
	//code
}  
	
复制

我们可以使用下图来理解 if 语句的流程。它表明只有在条件为真时,if 中编写的代码才会执行​​。

If Block的数据流图

例子:

在此示例中,我们正在测试学生的分数。如果分数大于 65,那么学生将获得第一名。


public class IfDemo1 {  
public static void main(String[] args) 
	{  
	int marks=70;  
	if(marks > 65)
		{  
		System.out.print("First division");  
		}  
	}  
}  
	
复制

if-else 语句

if-else 语句用于测试条件。如果条件为真,则执行 if 块,否则执行块。

当我们想根据错误结果执行一些操作时,它很有用。

else 块仅在条件为false时执行。

句法:


if(condition)
{  
	//code for true  
}
else
{  
	//code for false  
}  
	
复制

在这个框图中,我们可以看到,当条件为真时,如果块执行,否则执行块。

If Else 块的数据流图

if else 示例:

在此示例中,我们正在测试学生的分数,如果分数大于 65,则执行 if 块,否则执行块。


public class IfElseDemo1 {  
	public static void main(String[] args) 
	{  
		int marks=50;  
		if(marks > 65)
		{  
			System.out.print("First division");  
		}  
		else
		{  
			System.out.print("Second division");  
		}
	}  
}  
	
复制

if-else-if 阶梯语句

在 Java 中,if-else-if 梯形语句用于测试条件。它用于从多个语句中测试一个条件。

当我们有多个条件要执行时,建议使用 if-else-if 梯形图。

句法:


if(condition1)
{  
	//code for if condition1 is true  
}
else if(condition2)
{  
	//code for if condition2 is true  
}  
else if(condition3)
{  
	//code for if condition3 is true  
}  
...  
else
{  
	//code for all the false conditions   
}  
	
复制

它包含多个条件,如果任何条件为真则执行,否则执行 else 块。

If Else If Block的数据流图

例子:

在这里,我们正在测试学生的分数并根据获得的分数显示结果。如果分数大于 50 学生得到他的成绩。


public class IfElseIfDemo1 {  
public static void main(String[] args) {  
int marks=75;  
    if(marks<50){
System.out.println("fail");  
    }  
    else if(marks>=50 && marks<60){
System.out.println("D grade");  
    }  
    else if(marks>=60 && marks<70){
System.out.println("C grade");  
    }  
    else if(marks>=70 && marks<80){
System.out.println("B grade");  
    }  
    else if(marks>=80 && marks<90){
System.out.println("A grade");  
}else if(marks>=90 && marks<100){  
System.out.println("A+ grade");  
}else{  
System.out.println("Invalid!");  
    }  
}  
}  
	
复制

嵌套 if 语句

在 Java 中,嵌套的 if 语句是另一个 if 中的 if。在这种情况下,当外部块为真时,在另一个 if 块中创建一个 if 块,然后只执行内部块。

句法:


if(condition)
{    
     		//statement
     if(condition)
{  
             //statement 
    }    
}  
	
复制

嵌套 If 块的数据流图

例子:


public class NestedIfDemo1 {    
public static void main(String[] args) 
{      
int age=25;  
int weight=70;    
if(age>=18)
{    
if(weight>50)
{  
System.out.println("You are eligible");  
}    
}    
}	
}  
	
复制

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值