学习目标:
掌握 if else 条件判断的使用学习内容:
1、if语法
if(boolean表达式) {
语句体;
}
if后面的{}表示一个整体—代码块,称之为语句体,当boolean表达式为true,才执行这里的代码块。
public class IfDemo {
public static void main(String[] args) {
System.out.println("begin...");
// 定义一个变量
int a = 10;
// 如果a大于5,执行语句体的打印
if (a > 5) {
System.out.println("a大于5");
}
System.out.println("and...");
// 如果a大于20,执行语句体的打印
if (a > 20) {
System.out.println("a大于20");
}
System.out.println("ending...");
}
}
运行效果:
begin...
a大于5
and...
ending...
Process finished with exit code 0
2、if-else语法
if(boolean表达式) {
语句体1;
} else {
语句体2;
}
如果boolean表达式结果为true,就执行语句体1,否则执行语句体2。
代码如下:
public class IfElseDemo {
public static void main(String[] args) {
System.out.println("begin...");
// 定义一个变量
int a = 10;
// 如果变量a的值能被2整除,那么执行语句体的打印
if (a % 2 == 0) {
System.out.println("a是偶数");
} else {
//否则执行这里的语句体
System.out.println("a是奇数");
}
System.out.println("and...");
int b = 11;
if (b % 2 == 0) {
System.out.println("b是偶数");
} else {
System.out.println("b是奇数");
}
System.out.println("ending...");
}
}
运行效果:
begin...
a是偶数
and...
b是奇数
ending...
Process finished with exit code 0
3、if - else if - … - else 语法
if(boolean表达式1){
语句体1
} else if(boolean表达式2){
语句体2
}
... 可以有多个else if
else{
上述条件都为false,执行该语句体
}
流程图:
代码如下:
public class IfElseIfElseDemo1 {
public static void main(String[] args) {
System.out.println("begin...");
int a = 10; int b = 20;
if (a > b) {
System.out.println("a > b");
} else if (a < b) {
System.out.println("a < b");
} else {
System.out.println("a == b");
}
System.out.println("ending...");
}
}
运行效果:
begin...
a < b
ending...
Process finished with exit code 0
小例题:
/**
* 需求:根据天数输出qq等级
* [0,5) 无等级
* [5,12) ☆
* [12,21) ☆☆
* [21,32) ☆☆☆
* [32,~) ☾
*/
import java.util.Scanner;
public class IfElseIfElseDemo2 {
public static void main(String[] args) {
System.out.println("begin...");
if( days >= 32 ){
System.out.println("☾");
}else if( days >= 21){
System.out.println("☆☆☆");
}else if( days >= 12 ){
System.out.println("☆☆");
}else if( days >= 5){
System.out.println("☆");
}else{
System.out.println("无等级");
}
System.out.println("ending...");
}
}
总结:
if else 条件判断需要熟练掌握