初學者編寫城市距離查詢程式時,使用 while ((temp = in.next()) != "###") 判斷輸入結束。預期輸入 aaa bbb ccc ### 後停止讀取城市名,但實際運行時,後續的數字 0 1 2... 也被誤讀入 city 列表,導致邏輯錯誤。
!=在 Java 中,String 是物件,**不能使用 == 或 != 比較內容**,這些運算子比較的是記憶體地址。正確做法是使用 .equals() 方法。
Scanner in = new Scanner(System.in);
String temp = null;
System.out.println("請輸入城市(“###”結束輸入):");
// 使用 !temp.equals("###") 正確判斷字串內容
while (!(temp = in.next()).equals("###")) {
city.add(temp);
}
// 後續讀取距離矩陣邏輯...
input() 中關閉 Scanner:關閉後 System.in 流會被關閉,導致 main 中無法繼續讀取查詢城市。List 和 Map 介面宣告變數,提升程式彈性。containsKey 判斷鍵是否存在,避免空指標異常。public class CityDistance {
private List<String> city = new ArrayList<>();
private Map<String, Integer> distance = new HashMap<>();
public void input() {
Scanner in = new Scanner(System.in);
String temp;
System.out.println("請輸入城市(“###”結束輸入):");
while (!(temp = in.next()).equals("###")) {
city.add(temp);
}
int n = city.size();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
String key = city.get(i) + city.get(j);
System.out.print("請輸入 " + city.get(i) + " <--> " + city.get(j) + " 的距離:");
distance.put(key, in.nextInt());
}
}
// 此處不關閉 in
}
public int findDistance(String a, String b) {
String key = a + b;
return distance.getOrDefault(key, 0);
}
public static void main(String[] args) {
CityDistance cd = new CityDistance();
cd.input();
Scanner in = new Scanner(System.in);
System.out.print("輸入城市1:");
String a = in.next();
System.out.print("輸入城市2:");
String b = in.next();
System.out.println(a + " <--> " + b + " 的距離:" + cd.findDistance(a, b));
}
}
掌握字串比較正確姿勢,避開 Java 初學者最常見的坑!