首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >跟踪一个班级中有多少辆车被租用和可用

跟踪一个班级中有多少辆车被租用和可用
EN

Stack Overflow用户
提问于 2013-05-05 00:29:01
回答 2查看 574关注 0票数 0

我在使用这个代码时遇到了一些问题。这是我的java class.its的作业,已经过期了,但我只是想弄清楚这个问题,简直要发疯了。

问题:

当我将它上传到WileyPlus(自动批改服务器)时,它总是说当'int n= 14‘时,它期望结果是"24,15",但我得到的结果是"23,16“。然而,当我输入12时,我得到了预期的结果,即"7,5“。我似乎找不到是什么原因造成的。

有了代码,它就更有意义了。

代码语言:javascript
复制
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();
    }
}
EN

回答 2

Stack Overflow用户

发布于 2013-05-05 00:43:00

returnCar()中,你可以检查你想要还的车是不是租来的。在rentCar()中,您不会这样做。看起来你可以租一辆已经租好的车。尽量不要租已经租过的车。

票数 3
EN

Stack Overflow用户

发布于 2013-05-05 00:45:11

代码语言:javascript
复制
public boolean rentCar() {
    if (!rented) {
        availableCars--;
        rentedCars++;
        rented = true;
    }
    return rented;
}

(查看是否已在rentCar()中租车)

另外,我不理解返回值的用途,也就是说,你可以这样做

代码语言:javascript
复制
public void rentCar() {
    if (!rented) {
        availableCars--;
        rentedCars++;
        rented = true;
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16376478

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档