1:if基本選擇結(jié)構(gòu)
簡單條件下的if基本選擇結(jié)構(gòu)
if基本選擇結(jié)構(gòu)適用于“如果XX就XX”的情況
語法結(jié)構(gòu)
if(條件)
{
代碼塊//條件成立后要執(zhí)行的代碼,可以是一條語句,也可以是一組語句
}
案例:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.println("請輸入您的成績");
// System.out.println("程序中斷在這里 等待用戶從鍵盤輸入成績");
int score = scanner.nextInt();
if(score > 98){
System.out.println("獎勵一個巴掌");
}
}
}
2:復(fù)雜條件下的if基本選擇結(jié)構(gòu)
| 操作符 | 描述 | 例子 |
|---|---|---|
| && | 稱為邏輯與運算符。當(dāng)且僅當(dāng)兩個操作數(shù)都為真,條件才為真。 | (A && B)為假。 |
| | | | 稱為邏輯或操作符。如果任何兩個操作數(shù)任何一個為真,條件為真。 | (A | | B)為真。 |
| ! | 稱為邏輯非運算符。用來反轉(zhuǎn)操作數(shù)的邏輯狀態(tài)。如果條件為true,則邏輯非運算符將得到false。 | !(A && B)為真。 |
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
int score = 100 ;
int score2 = 78;
if((score > 98 && score2 >85)||(score == 100 && score2 >75)){
System.out.println("獎勵一個巴掌");
}
}
}
2:if else 選擇結(jié)構(gòu)
if(條件1){
代碼塊1
}else{
代碼塊
}
package edu.xcdq;
import java.util.Scanner;
public class Demo06 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("請輸入您的成績");
// System.out.println("程序中斷在這里 等待用戶從鍵盤輸入成績");
int score = scanner.nextInt();
if (score > 80) {
System.out.println("良好");
} else {
System.out.println("差");
}
}
}
3:多重if選擇結(jié)構(gòu)
if(條件1){
代碼塊1
}else if(條件20){
代碼塊2
}else{
代碼塊3
}
注意
1:else 塊 做多有一個或沒有,else塊必須要放在else if塊之后
2:else if最多可以有多個或沒有,需要幾個else if 塊完全取決于需要
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.println("請輸入您的成績");
// System.out.println("程序中斷在這里 等待用戶從鍵盤輸入成績");
int score = scanner.nextInt();
if(score > 80){
System.out.println("良好");
}else if(score >=60 ){
System.out.println("中等");
}else{
System.out.println("差");
}
}
4:嵌套if 選擇結(jié)構(gòu)
if(條件 1){
if(條件 2){
代碼塊1
} else {
代碼塊2
}
}else{
代碼塊3
}
注意:
1:只有當(dāng)滿足外層if選擇結(jié)構(gòu)的條件時,才會判斷內(nèi)層if的條件
2:else總是跟他前面最近的那個缺少else的if配對
package edu.xcdq;
import java.util.Scanner;
public class Demo06 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("請輸入比賽成績(s):");
double score = input.nextDouble();
System.out.println("請輸入性別:");
String gender = input.next();
if (score <=10) {
if(gender.equals("男")){
System.out.println("進入男子組決賽");
}else if(gender.equals("女")) {
System.out.println("進入女子組決賽");
}
} else {
System.out.println("淘汰");
}
}
}