• For迴圈:
    1
    2
    3
    for (int i = 0; i < 10; i++) {
    System.out.println(i);
    }
  • 迴圈(While迴圈和Do-While迴圈):

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    // While迴圈
    int i = 0;
    while (i < 5) {
    System.out.println(i);
    i++;
    }

    // Do-While迴圈
    int j = 0;
    do {
    System.out.println(j);
    j++;
    } while (j < 5);
  • If else:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    int number = 10;

    if (number > 0) {
    System.out.println("Number is positive");
    } else if (number < 0) {
    System.out.println("Number is negative");
    } else {
    System.out.println("Number is zero");
    }

    -陣列:

    1
    2
    3
    4
    5
    int[] numbers = {1, 2, 3, 4, 5};

    for (int i = 0; i < numbers.length; i++) {
    System.out.println(numbers[i]);
    }
  • 字串處理:

    1
    2
    3
    4
    5
    6
    String message = "Hello, world!";

    System.out.println(message.length()); // 字串長度
    System.out.println(message.toUpperCase()); // 轉換為大寫
    System.out.println(message.substring(7, 12)); // 取得子字串
    System.out.println(message.indexOf("world")); // 搜尋字串位置
  • 類別和物件:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    class Car {
    String brand;
    String color;

    void startEngine() {
    System.out.println("Engine started");
    }
    }

    Car myCar = new Car();
    myCar.brand = "Toyota";
    myCar.color = "Red";
    myCar.startEngine();
  • 方法和參數:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    class Calculator {
    int add(int a, int b) {
    return a + b;
    }
    }

    Calculator calc = new Calculator();
    int result = calc.add(5, 3);
    System.out.println(result); // 輸出:8
  • 例外處理:

    1
    2
    3
    4
    5
    6
    7
    try {
    // 可能會拋出例外的程式碼
    int result = 10 / 0;
    } catch (ArithmeticException e) {
    // 捕捉並處理例外
    System.out.println("發生除以零的錯誤:" + e.getMessage());
    }