// 檔名:PZ.java // === 常數與主要設定 === public class PZ { private static final int SAFE_DISTANCE = 15; // 安全距離 (單位:公分) public static void main(String[] args) { PZ car = new PZ(); car.run(); } // === 自走車運行邏輯 === public void run() { while (true) { int distance = getDistanceFromSensor(); // 從傳感器獲取距離 if (distance < SAFE_DISTANCE) { stopMotors(); // 停止車輛 turnRight(); // 右轉 } else { moveForward(); // 繼續向前 } waitMilliseconds(500); // 等待 500 毫秒 } } // === 距離檢測模塊 === private int getDistanceFromSensor() { // 模擬超聲波傳感器測量距離 return (int) (Math.random() * 50); // 隨機生成一個距離值 (0-50 cm) } // === 馬達控制模塊 === private void moveForward() { System.out.println("Moving forward..."); // 添加控制馬達向前的實際邏輯 } private void stopMotors() { System.out.println("Stopping motors..."); // 添加停止馬達的實際邏輯 } private void turnRight() { System.out.println("Turning right..."); // 添加控制馬達右轉的實際邏輯 } // === 工具函數模塊 === private void waitMilliseconds(int milliseconds) { try { Thread.sleep(milliseconds); // 暫停程式執行一段時間 } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }