2010-10-29 148 views
0

我試圖檢查一個加油泵是否可以免費使用& &滿了氣,然後我試着讓那個加油泵讓汽車在排隊時使用。爲什麼我的if語句不起作用?

Thread carThreads[]=new Thread[TOTAL_CARS]; 
    try { 
    Pump pump1 = new Pump(); 
    pump1.setName("pump1"); 
    pump1.setFuelAmount(2000); 
    pump1.setState(0); 

    Pump pump2 = new Pump(); 
    pump2.setName("pump2"); 
    pump2.setFuelAmount(2500); 
    pump2.setState(0); 

    Pump chosenPump = new Pump(); 

    if(pump1.getState()==0 && pump1.getFuelAmount()<0){ 
     chosenPump = pump1; 
     System.out.println("Pump1 is free and has a fuel amount of: " 
     + (pump1.getFuelAmount())); 
    } 

    else if (pump2.getState()==0 && pump2.getFuelAmount()<0){ 
     chosenPump = pump2; 
     System.out.println("Pump2 is free and has a fuel amount of: " 
     + (pump2.getFuelAmount())); 
    } 
    //else{ 
    // System.out.println("Must wait for the tanker. It should be here soon"); 
    //} 

    Random r = new Random(); 

    Car car; 

    for(int i = 0; i<TOTAL_CARS; i++){ 
     car = new Car(i, chosenPump); 
     System.out.println("car" + car.getID() + " was created"); 

     (carThreads[i] = new Thread(car)).start(); 
     Thread.currentThread().sleep(r.nextInt(10000)); 

     line.enqueue(car); 

     chosenPump.usePump((Car)line.getfirst(), chosenPump, line); 

     System.out.println("this is the new line size for gas: " + line.size()); 
    }//end for 
    }//end try 
    catch (Exception e){ 
    } 
}//end of main 
+2

如果聲明不起作用?有沒有錯誤?我們需要更多細節。 – 2010-10-29 18:58:32

回答

13

要檢查pump1.getFuelAmount()<0

這將檢查泵是否有負量燃油。如果你想看看它是否有燃料的正數,你需要做的pump1.getFuelAmount()>0pump2.getFuelAmount()>0

+0

哦,我的天啊,謝謝!!!!!!!!!!!! – Luron 2010-10-29 19:19:11

6

也許你想

if(pump1.getState() == 0 && pump1.getFuelAmount() > 0) { 

,而不是

if(pump1.getState() == 0 && pump1.getFuelAmount() < 0) { 

(你已經混了><

-1

變化pump1.getFuelAmount()< 0至pump1.getFuelAmount()> 0 同爲泵2

+1

爲什麼張貼你自己的答案,某人已經發布的東西? – 2010-10-29 19:17:58

3

重寫您if()聲明,如下所示:

if(pump1.getState() == 0 && pump1.getFuelAmount() > 0) { 
    chosenPump = pump1; 
    System.out.println("Pump1 is free and has a fuel amount of: " 
     + (pump1.getFuelAmount())); 
} else if(pump2.getState() == 0 && pump2.getFuelAmount() > 0) { 
    chosenPump = pump2; 
    System.out.println("Pump2 is free and has a fuel amount of: " 
     + (pump2.getFuelAmount())); 
} 

您可能還需要包括在最後一個包羅萬象else這樣你就可以處理,如果沒有泵是否可用,如果既沒有燃料。

0

一對夫婦的意見:

首先,泵1和泵2。不會有一組泵減少代碼量? (你可以使用循環來檢查你所有的泵是否有任何東西)

在你的if語句中:理論上,你不能有負數的燃料,所以你想要做的就是看你是否有超過0。 (如果你小於0,你不能再給燃料了,所以它不會超過0多少)

相關問題