条件分支控制一般有 2 种:if-else条件分支和switch选择分支。
1. if-else条件分支
一般情况下,基于if-else的条件分支也有 3 种形式,分别为单分支、双分支以及多分支。
1.1 单分支
如果我们只有一个if条件判断,这样的流程控制称为单分支的条件控制。
public class SingleConditionBranchControl {public static void main(String[] args) {int num = 10;if (num > 5) {System.out.println("This is single branch condition control!");}}}
1.2 双分支
如果使用if...else...这样的条件判断,这样的流程控制称为双分支的条件控制。
public class DoubleBranchControl {public static void main(String[] args) {int num = 10;if (num > 5) {System.out.println("This is first branch control");} else {System.out.println("This is second branch control");}}}
1.3 多分支
如果使用if...else if...else这样的条件判断,这样的流程控制称为多分支的条件控制。
public class MultiBranchControl {public static void main(String[] args) {int num = 10;if (num > 8) {System.out.println("This is first branch control");} else if (num > 5) {System.out.println("This is second branch control");} else {System.out.println("This is third branch control");}}}
1.4 嵌套分支
当然,我们还可以在分支中继续嵌套分支,所嵌套的分支可以是单分支、双分支、多分支其中的一种或多种。
public class NestBranchControl {public static void main(String[] args) {int age = 18;float height = 1.75f;if (age > 18) {System.out.println("You are less than 18 years old!");} else {if (height < 1.2) {System.out.println("Your are too short!");} else if (height > 1.8) {System.out.println("Your are strong!");} else {System.out.println("You grow healthily!");}}}}
1.5 练习
接下来,我们做一个小练习,根据用户输入的身高和体重,算出该用户的 BMI 值。如果所计算的 BMI 与标准严重不符合,需警告用户注意身体。
import java.util.Scanner;public class CalculateBMI {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.print("Input your height: ");float height = scanner.nextFloat();System.out.print("Input your weight: ");float weight = scanner.nextFloat();double bmi = (weight / Math.pow(height, 2));System.out.println("BMI Standard Range: 18.5 ~ 23.9");System.out.println("Your BMI Value is " + bmi + "\n");if (bmi < 18.5) {System.out.println("You are too thin, and need to be more stronger!");} else if (bmi > 23.9) {System.out.println("You are too fat, and need to reduce your weight!");} else {System.out.println("Your are very healthy!");}}}
上面高亮的代码部分,用来定义一个Scanner等待用户输入,这个和 Python 种input非常类似。
2. switch多分支
另一种条件分支就是switch选择分支,其实能用switch实现的分支逻辑都可以用if-else来实现,只不过有些情况下,switch选择分支的代码会更间接一些。
另外值得一提的是,switch分支是基于值的分支,并不能做比较判断:
public class SwitchBranchControl {public static void main(String[] args) {String fruit = "apple";switch (fruit) {case "apple":System.out.println("This is an apple!");break;case "banana":System.out.println("This is a banana!");break;default:System.out.println("This is a fruit?");}}}
其中default分支表示前面的分支都没有击中的情况下,则会击中该分支。当然,default分支也可以选择不添加。
