2024-07-04|閱讀時間 ‧ 約 29 分鐘

Java入門-Day6:流程控制

if, else if, else

ifelse ifelse語句用於根據條件執行不同的代碼塊。以下是使用這些語句的範例:

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語句用於根據多個條件執行不同的代碼塊。以下是使用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迴圈用於重複執行某些代碼,直到條件不滿足為止。以下是使用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迴圈

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);
}
}
}
}

控制迴圈語句

在迴圈中,可以使用breakcontinuereturn語句來控制迴圈的執行。

  • 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);
}
}
}

分享至
成為作者繼續創作的動力吧!
© 2024 vocus All rights reserved.