if 语句

Java 中级

Jim White

Java Developer

控制流

条件为 true ✅ ➜ 执行操作

条件为 false ❌ ➜ 不执行

Java 中级

if 的工作原理

若分数 ≥ 90 ➜ 打印 "Great job!"

若分数 < 90 ➜ 不打印

Java 中级

if 语句结构

if (condition) {
  // Code to run
}

如果条件为 true,大括号内的代码会运行

Java 中级

条件

  • 使用比较运算符,如 ==!=><>=<=
// 当 score >= 90 时打印 "Great job!"
if (score >= 90) {
  System.out.println("Great job!");  
}
Java 中级

if 与 if 与 if …

int score = 94;

if (score >= 90) {
  System.out.println("Excellent!");  
}

if (score >= 70) {
  System.out.println("Good job!");  
}

if (score < 70) {
  System.out.println("Try again!");  
}
Excellent!
Good job!
  • 两条消息都会显示,因为两个条件都满足
Java 中级

回顾

我们可以有不同条件,只要它们计算为 true / false

if (score != 0){
  System.out.println("Well, you got some points!");
}

if (message.equals("F")){
  System.out.println("Try again!");
}

if (testResult == 100) {
  System.out.println("Wow, you got it all!");
}
Java 中级

¡Vamos a practicar!

Java 中级

Preparing Video For Download...