在 Java 程序设计中,通常将程序的基本结构归纳为三大类:顺序结构、选择结构和循环结构。以下是每种结构的简要介绍和示例:
1. 顺序结构 (Sequential Structure)
顺序结构是程序中最基本的控制结构,指令按先后顺序依次执行。
public class SequentialExample {
public static void main(String[] args) {
System.out.println("Start");
System.out.println("Step 1");
System.out.println("Step 2");
System.out.println("End");
}
}
2. 选择结构 (Selection Structure)
选择结构根据条件的真假来决定执行哪一部分代码。常见的选择结构有 if
、if-else
和 switch
。
public class SelectionExample {
public static void main(String[] args) {
int score = 85;
// if-else structure
if (score >= 90) {
System.out.println("Grade: A");
} else if (score >= 80) {
System.out.println("Grade: B");
} else if (score >= 70) {
System.out.println("Grade: C");
} else {
System.out.println("Grade: D or F");
}
// switch structure
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Another day");
break;
}
}
}
3. 循环结构 (Loop Structure)
循环结构用于重复执行某段代码。常见的循环结构有 for
、while
和 do-while
。
public class LoopExample {
public static void main(String[] args) {
// for loop
for (int i = 0; i < 5; i++) {
System.out.println("For Loop Iteration: " + i);
}
// while loop
int j = 0;
while (j < 5) {
System.out.println("While Loop Iteration: " + j);
j++;
}
// do-while loop
int k = 0;
do {
System.out.println("Do-While Loop Iteration: " + k);
k++;
} while (k < 5);
}
}
增强的 switch
表达式
Java 12 引入了增强的 switch
表达式,使得 switch
语句更加简洁和强大。我们可以直接返回值,并且支持箭头语法。
public class EnhancedSwitchExample {
public static void main(String[] args) {
int day = 3;
String dayName = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
case 4 -> "Thursday";
case 5 -> "Friday";
case 6 -> "Saturday";
case 7 -> "Sunday";
default -> "Invalid day";
};
System.out.println("Day name: " + dayName);
}
}
增强的 for
循环(for-each
循环)
增强的 for
循环用于迭代数组或集合中的元素,更加简洁和易读。
import java.util.Arrays;
import java.util.List;
public class EnhancedForExample {
public static void main(String[] args) {
// Example with an array
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
System.out.println("Number: " + number);
}
// Example with a list
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
for (String name : names) {
System.out.println("Name: " + name);
}
}
}
结合增强的 switch
和 for-each
循环
我们还可以结合使用增强的 switch
表达式和 for-each
循环,编写更加简洁和高效的代码。
import java.util.Arrays;
import java.util.List;
public class CombinedExample {
public static void main(String[] args) {
List<Integer> days = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
for (int day : days) {
String dayName = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
case 4 -> "Thursday";
case 5 -> "Friday";
case 6 -> "Saturday";
case 7 -> "Sunday";
default -> "Invalid day";
};
System.out.println("Day " + day + " is " + dayName);
}
}
}