我正在尝试检查气泵是否可以免费使用&&充满了汽油,然后我试图让那个泵成为汽车排队使用的泵。
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
答案 0 :(得分:13)
您正在查看pump1.getFuelAmount()<0
这将检查泵是否有负燃料量。如果你想查看它是否有正燃料量,你需要pump1.getFuelAmount()>0
和pump2.getFuelAmount()>0
答案 1 :(得分:6)
也许你想要
if(pump1.getState() == 0 && pump1.getFuelAmount() > 0) {
而不是
if(pump1.getState() == 0 && pump1.getFuelAmount() < 0) {
(你混淆了>
和<
)
答案 2 :(得分: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
,以便在没有泵可用或者两者都没有燃料的情况下处理。
答案 3 :(得分:0)
几条评论:
首先,pump1和pump2。一系列泵不会减少代码量吗? (您可以使用循环检查所有泵的任何东西)
关于你的if语句:从理论上讲,你不能有负数的燃料,所以你要做的就是看你是否有超过0.(如果你的数量少于0,你就不能再给燃料了无论如何,所以它低于0并不重要)
答案 4 :(得分:-1)
将pump1.getFuelAmount()&lt; 0更改为pump1.getFuelAmount()&gt; 0 对于pump2来说是相同的