2013-05-04 53 views
0

我一直有這個代碼的麻煩。這是我的java class.its過去的任務,但我只是想搞清楚這個問題。跟蹤多少輛車出租並在一個類中提供

問題:

當我把它上傳到WileyPlus(自動糾錯服務器),它口口聲聲說,當「INT N = 14」這是預期的結果是「24,15」,但我得到「23 ,16「。但是,當我輸入12時,我會得到預期的結果,即「7,5」。我似乎無法找到造成這種情況的原因。

隨着代碼,它會更有意義。

public class RentalCar { 
    private boolean rented; 
    private static int availableCars = 0; 
    private static int rentedCars = 0; 

    public RentalCar() { 
     availableCars++; 
     rented = false; 
    } 

    public static int numAvailable() { 
     return availableCars; 
    } 

    public static int numRented() { 
     return rentedCars; 
    } 

    public boolean rentCar() { 
     availableCars--; 
     rentedCars++; 
     rented = true; 
     return rented; 
    } 

    public boolean returnCar() { 
     if (rented) { 
      availableCars++; 
      rentedCars--; 
      rented = false; 
     } 

     return false; 
    } 

    public static String check(int n) { 
     RentalCar[] cars = new RentalCar[n]; 
     for (int i = 0; i < n; i++) { 
      cars[i] = new RentalCar(); 
     } 

     for (int i = 0; i < n; i = i + 2) { 
      cars[i].rentCar(); 
     } 

     for (int i = 0; i < n; i = i + 3) { 
      cars[i].rentCar(); 
     } 

     for (int i = 0; i < n; i = i + 4) { 
      cars[i].returnCar(); 
     } 

     return RentalCar.numRented() + " " + RentalCar.numAvailable(); 
    } 
} 
+0

的每個實例您創建的「RentalCar」將具有相同的「availableCars」和「rentedCars」值。 – Makoto 2013-05-04 16:32:07

+0

@Makoto:這部分似乎是正確的。 – jlordo 2013-05-04 16:37:27

+0

@Makoto我認爲這是重點;它跟蹤計數。 – 2013-05-04 16:39:03

回答

3

returnCar()您檢查,如果您試圖返回的汽車是出租。在rentCar()你不這樣做。看來你可以租一輛已租用的汽車。儘量防止租用已經租用的汽車。

+0

謝謝!我得到它的工作! – Rimshot 2013-05-04 17:53:06

+0

@Rimshot:我希望你不要忘記接受一個答案...... – jlordo 2013-05-04 17:59:08

0
public boolean rentCar() { 
    if (!rented) { 
     availableCars--; 
     rentedCars++; 
     rented = true; 
    } 
    return rented; 
} 

(檢查車在rentCar()已經租用)

另外,我不明白的返回值的目的,即你不妨做

public void rentCar() { 
    if (!rented) { 
     availableCars--; 
     rentedCars++; 
     rented = true; 
    } 
} 
+0

也許他的意思是返回值來表示操作是否成功(儘管這不是它所做的)。 – 2013-05-04 16:48:17