學習目標:
掌握 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 條件判斷需要熟練掌握