2011-08-21 90 views
1

我得到這個功能,這是一個private boolean函數,檢查車庫內是否已經有相同大小的汽車。如果沒有,我將它添加到arrayList,我已經做了printList()類型的函數,然後遍歷arraylist並打印出值(這很好用),但不知怎的,我的private boolean函數似乎根本不起作用。Java比較兩個字符串似乎不起作用

繼承人我的代碼:

public class Cars { 

    public Cars (String size, boolean booking) { 
     this.carSize = size; 
     this.isBooked = booking; 
    } 

    public String getSize() { 
     return this.carSize; 
    } 

    public boolean checkBook() { 
     return this.isBooked; 
    } 

    private String carSize; 
    private boolean isBooked; 

} 

public class Locations { 

    public Locations (String curLocation) { 
     garage = new ArrayList<Cars>(); 
     location = curLocation; 
    } 

    public void addCar (String size, boolean booking) { 
     if (garage.isEmpty() || !checkCar(size)) { 
      garage.add(new Cars(size, booking)); 
      System.out.println("Car assigned " + location + " " + size); 
     } 
    } 

    private boolean checkCar (String size) { 
     for (Cars car : garage) { 
      System.out.println("hey"); 
      if (size.equals(car.getSize())) return true; 
     } 
     return false; 
    } 

    private ArrayList <Cars> garage; 
    private String location; 

} 

輸入是爲以下幾點:

Car small City 
Car small Redfern 
Car small Redfern 

輸出:

Car assigned City small 
Car assigned Redfern small 
Car assigned Redfern small 

它不應該打印出第二雷德芬小,因爲有已經是名單內的那輛車。

+2

順便說一下,'Cars'類不應該是複數。 – SLaks

+0

需要你的整個代碼。 –

+0

沒有看到你的主要方法,很難說它有什麼問題。也許你在第三行有額外的空間?你能在平等比較之前調整它嗎? – CoolBeans

回答

1

(我以前的答案是錯了 - 我誤讀了代碼,我曾急促......)

我能想到的只有一個正在發生的事情說明:

你叫new Locations("Redfern")兩次。

這可以解釋爲什麼你看到的消息Car assigned Redfern small兩次,爲什麼你沒有看到hey

您可以通過將一個traceprint在Locations構造證實了這一點......


該理論認爲,這是由前/後空格上size串根本站不住腳之一引起的。如果這是問題,則OP會看到hey,因爲checkCar方法重複了​​列表。

+0

@Paul Equis - 固定。 –

1

如果我用下面的方式代碼:

public class Main 
{ 
    public static void main(String[] args) 
    { 
     Locations locationsCity = new Locations("City"); 
     locationsCity.addCar("small", true); 
     Locations locationsRedfern = new Locations("Redfern"); 
     locationsRedfern.addCar("small", true); 
     locationsRedfern.addCar("small", true); 
    } 
} 

這是我得到的輸出:

Car assigned City small 
Car assigned Redfern small 
hey 

這似乎只是罰款,並根據您的代碼。

+0

我相信OP可能會爲他們的例子中的每一行輸入創建一個全新的Locations對象。這將解釋他們正在顯示的輸出。 –

+0

我也假設: 'Locations locationsRedfern1 = new Locations(「Redfern」); locationsRedfern1。addCar(「small」,true); 位置locationsRedfern2 =新位置(「Redfern」); locationsRedfern2.addCar(「small」,true);' 只會得到他所得到的結果。 – ZenMaster

+0

嗯,可能是這種情況,因爲我每次都在創建一個新的位置對象 – FHr

0

考慮把你的汽車放在一個集合中,並實現equals()來使用String.equals()方法檢查大小。