首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Java 而循環無法終止?字串比較錯誤導致的經典陷阱

     編輯:程式設計綜合問答

問題現象

初學者編寫城市距離查詢程式時,使用 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 初學者最常見的坑!

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved