我在使用此代码时遇到了一些麻烦。这是我的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 :(得分:3)
在returnCar()
中,您检查是否租用了您要返回的汽车。在rentCar()
,你不这样做。看来你可以租一辆已租的汽车。尽量避免租用已租用的汽车。
答案 1 :(得分:0)
public boolean rentCar() {
if (!rented) {
availableCars--;
rentedCars++;
rented = true;
}
return rented;
}
(检查汽车是否已在rentCar()
租用)
另外,我不明白返回值的目的,即你也可以这样做
public void rentCar() {
if (!rented) {
availableCars--;
rentedCars++;
rented = true;
}
}