if
、else if
和else
語句用於根據條件執行不同的代碼塊。以下是使用這些語句的範例:
public class IfElseExample {
public static void main(String[] args) {
int number = 10;
if (number > 0) {
System.out.println("The number is positive.");
} else if (number < 0) {
System.out.println("The number is negative.");
} else {
System.out.println("The number is zero.");
}
}
}
三元運算子是一種簡潔的條件語句,用於代替簡單的if-else
語句。語法為condition ? expr1 : expr2
。
public class TernaryOperatorExample {
public static void main(String[] args) {
int number = 10;
String result = (number > 0) ? "positive" : "negative";
System.out.println("The number is " + result);
}
}
switch
語句用於根據多個條件執行不同的代碼塊。以下是使用switch
語句的範例:
public class SwitchExample {
public static void main(String[] args) {
int day = 3;
String dayName;
switch (day) {
case 1:
dayName = "Sunday";
break;
case 2:
dayName = "Monday";
break;
case 3:
dayName = "Tuesday";
break;
case 4:
dayName = "Wednesday";
break;
case 5:
dayName = "Thursday";
break;
case 6:
dayName = "Friday";
break;
case 7:
dayName = "Saturday";
break;
default:
dayName = "Invalid day";
break;
}
System.out.println("The day is " + dayName);
}
}
for
迴圈用於重複執行某些代碼,直到條件不滿足為止。以下是使用for
迴圈的範例:
public class ForLoopExample {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println("i = " + i);
}
}
}
foreach的範例
public class ForEachArrayExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
System.out.println(number);
}
}
}
while
迴圈用於重複執行某些代碼,只要條件為true
。以下是使用while
迴圈的範例:
public class WhileLoopExample {
public static void main(String[] args) {
int i = 0;
while (i < 5) {
System.out.println("i = " + i);
i++;
}
}
}
可以在一個循環內嵌套另一個循環。以下是嵌套for
迴圈的範例:
public class NestedLoopsExample {
public static void main(String[] args) {
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.println("i = " + i + ", j = " + j);
}
}
}
}
在迴圈中,可以使用break
、continue
和return
語句來控制迴圈的執行。
break
語句:立即終止迴圈。continue
語句:跳過當前迴圈迭代,繼續下一次迭代。return
語句:終止方法,並返回指定值(如果有)。範例程式碼:
public class LoopControlExample {
public static void main(String[] args) {
// break示例
for (int i = 0; i < 10; i++) {
if (i == 5) {
break;
}
System.out.println("i (with break) = " + i);
}
// continue示例
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue;
}
System.out.println("i (with continue) = " + i);
}
// return示例
for (int i = 0; i < 10; i++) {
if (i == 5) {
return; // 終止方法
}
System.out.println("i (with return) = " + i);
}
}
}