if语句
一个if语句包含一个布尔表达式和一条或多条语句。
语法
If语句的用语法如下:
if(布尔表达式)
{
//如果布尔表达式为true将执行的语句
}
如果布尔表达式的值为true,则执行if语句中的代码块。否则执行If语句块后面的代码。
1
2
3
4
5
6
7
8
9
10
|
public class Test {
public static void main(String args[]){
int x = 10 ;
if ( x < 20 ){
System.out.print( "这是 if 语句" );
}
}
}
|
以上代码编译运行结果如下:
1
|
这是 if 语句
|
if...else语句
if语句后面可以跟else语句,当if语句的布尔表达式值为false时,else语句块会被执行。
语法
if…else的用法如下:
if(布尔表达式){
//如果布尔表达式的值为true
}else{
//如果布尔表达式的值为false
}
实例
1
2
3
4
5
6
7
8
9
10
11
12
|
public class Test {
public static void main(String args[]){
int x = 30 ;
if ( x < 20 ){
System.out.print( "这是 if 语句" );
} else {
System.out.print( "这是 else 语句" );
}
}
}
|
最简单的if-else语句示例
假设我到办公室里问黄文强在不在?如果他在的话会说在,不在的时候有热心同事回答了一句“他不在”,那我就不立刻明白了。我们用程序模拟一下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
public class demo {
public static void main(String[] args) {
//设置黄文强不在
boolean flag = false ;
System.out.println( "开始" );
if (flag){
System.out.println( "在" );
} else {
System.out.println( "他不在" );
}
System.out.println( "结束" );
}
}
|