Logo
Section 1 / 13

条件语句

学习使用 if、else 以及现代 switch 表达式来控制程序流程,根据特定条件执行代码。

导入

条件语句

学习使用 if、else 以及现代 switch 表达式来控制程序流程,根据特定条件执行代码。

...
A single condition controls whether a block of code runs or is skipped entirely
1public class TemperatureCheck { 2 public static void main(String[] args) { 3 int currentTemperature = 35; 4 int threshold = 30; 5 6 // Simple if statement 7 if (currentTemperature > threshold) { 8 System.out.println("Warning: It is hot outside!"); 9 } 10 11 System.out.println("System check complete."); 12 } 13}
...
A decision splits into two exclusive paths, ensuring that exactly one of the two blocks is executed
1public class PassFailCheck { 2 public static void main(String[] args) { 3 int score = 45; 4 5 if (score >= 50) { 6 System.out.println("Result: Pass"); 7 } else { 8 System.out.println("Result: Fail"); 9 } 10 } 11}
...
A sequential chain that tests a series of conditions one by one, executing the code for the first true match it finds and ignoring the rest
1public class GradingSystem { 2 public static void main(String[] args) { 3 int score = 75; 4 5 if (score >= 90) { 6 System.out.println("Grade: Distinction"); 7 } else if (score >= 70) { 8 System.out.println("Grade: Merit"); 9 } else if (score >= 50) { 10 System.out.println("Grade: Pass"); 11 } else { 12 System.out.println("Grade: Fail"); 13 } 14 } 15}
1public class ScopeCheck { 2 public static void main(String[] args) { 3 boolean accessGranted = true; 4 5 if (accessGranted) { 6 String message = "Welcome, Admin"; // Variable defined inside the block 7 System.out.println(message); 8 } 9 10 // System.out.println(message); // ERROR: 'message' cannot be resolved here 11 } 12}
...
A single input value is matched against multiple labeled options to determine which code path to follow
1public class DayPlanner { 2 public static void main(String[] args) { 3 int dayOfWeek = 3; // 1 = Monday, 7 = Sunday 4 String schedule; 5 6 switch (dayOfWeek) { 7 case 1: 8 schedule = "Gym"; 9 break; 10 case 2: 11 schedule = "Team Meeting"; 12 break; 13 case 3: 14 schedule = "Coding Focus"; 15 break; 16 default: 17 schedule = "Free Time"; 18 break; 19 } 20 System.out.println("Today's plan: " + schedule); 21 } 22}
1public class ModernDayPlanner { 2 public static void main(String[] args) { 3 int dayOfWeek = 3; 4 5 switch (dayOfWeek) { 6 case 1 -> System.out.println("Gym"); 7 case 2 -> System.out.println("Team Meeting"); 8 case 3 -> { 9 System.out.println("Coding Focus"); 10 System.out.println("Do not disturb"); 11 } 12 default -> System.out.println("Free Time"); 13 } 14 } 15}

高级面向对象特性

迭代语句