您的位置:首页 > 编程语言 > Java开发

Java技术_Java千百问(0017)_if else如何使用

2016-03-31 21:15 696 查看
点击进入_更多_Java千百问

if else如何使用

java中if else语句,是用来做逻辑判断的语法(另一种逻辑判断语句switch看这里:switch如何使用)。使用方式非常简单,可以用if做单独判断,可以用if...else
if...else做多逻辑判断,还可以嵌套使用。可以说是java中使用最为广泛的语句。下面来说明这个语句具体如何使用。

1、if语句如何单独使用:

首先,if语句的语法为:

if(Boolean flag)
{
//如果flag为true时,进入这里,执行{}包起来的代码段;如果为false,则直接跳过,不执行该段。

}
这里要注意的是,如果{}包起来的代码只有一句,则可以省略{},但是这种写法一般不建议写。

实例:

public class Test {

public static void main(String args[]){
int x = 10;

if(true){
System.out.print("==1==");
}

  if( x >= 20 )
System.out.print(" ==2==");

System.out.print(" ==3==");

  if( x < 20 )
System.out.print(" ==4==");
}
}
将会产生以下结果:

==1==

==3==

==4==

2、if...else if...else 语句:

if语句后面可以跟一个可选的else if...else语句。

else if...可以添加多个,用来判断不同的逻辑;else...一组if条件中只能有一个,没有被前面的条件匹配到,则会执行else里的代码。当然直接if....else....也是可以的。

它的语法是:

if(Boolean flag1){
//如果flag1为true时,进入这里,执行{}包起来的代码段;如果为false,则继续判断下面的else if条件。
}
else if(Boolean flag2){
 //如果flag2为true时,进入这里(当然前提是flag1为false),执行{}包起来的代码段;如果为false,则继续判断下面的else if条件。
}
else if(Boolean flag3){
 //同上一个else if,前提是flag1、flag2都为false。
}
...
else{
//如果flag1、flag2、flag3...都为false,则执行这里。

}
实例:
public class Test {

public static void main(String args[]){
int x = 30;

if( x == 10 ){
System.out.print("==1==");
}
}else if( x == 20 ){
System.out.print(" ==2==");
}else if( x == 30 ){
System.out.print(" ==3==");
  else{
System.out.print(" ==4==");
}
}
}
这将产生以下结果:

==3==

3、嵌套语句:

你可以在一个if或else if语句中使用另一个if或else if语句。

语法:

嵌套if...else的语法如下:

if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}
}

可以嵌套else if...else在类似的方式,因为我们有嵌套的if语句。

实例:

public class Test {

public static void main(String args[]){
int x = 30;
int y = 10;

if( x == 30 ){
if( y == 10 ){
System.out.print("X = 30 and Y = 10");
}
}
}
}
这将产生以下结果:

X = 30 and Y = 10

点击进入ooppookid的博客
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: