優勢:明確需求、重構安全、單元測試天然形成。
public class SimpleDotCom {
private int[] locationCells; // 佔用格位
private int numOfHits = 0; // 命中計數
public void setLocationCells(int[] cells) { this.locationCells = cells; }
public String checkYourself(int userGuess) {
String result = "miss";
for (int cell : locationCells) {
if (cell == userGuess) {
result = "hit";
numOfHits++;
break;
}
}
if (numOfHits == 3) result = "kill";
return result;
}
}
public class Test {
public static void main(String[] args) {
SimpleDotCom dotCom = new SimpleDotCom();
dotCom.setLocationCells(new int[]{2, 3, 4});
System.out.println(dotCom.checkYourself(2)); // hit
System.out.println(dotCom.checkYourself(3)); // hit
System.out.println(dotCom.checkYourself(4)); // kill
}
}
// Java 中 -3 % 2 == -1,不可用 num % 2 == 1 判斷奇數
// 正確寫法:
num % 2 == 0 // 偶數
num % 2 != 0 // 奇數
Math.abs(num) % 2 == 1 // 亦可
Python 中 -3 % 2 == 1,語言特性不同需注意。
「偽代碼 → 測試 → 實作」流程讓邏輯清晰、品質可控,值得養成習慣。