public class ChickenRabbitPen { private int chickenCount; private int rabbitCount; private int totalCount;

public ChickenRabbitPen(int totalCount, int totalLegs) throws Exception {
    if (totalLegs % 2 != 0) {
        throw new Exception("总腿数必须为偶数");
    }
    this.totalCount = totalCount;
    this.rabbitCount = (totalLegs - totalCount * 2) / 2;
    this.chickenCount = totalCount - rabbitCount;
}

public int getChickenCount() {
    return chickenCount;
}

public int getRabbitCount() {
    return rabbitCount;
}

public static void main(String[] args) {
    try {
        ChickenRabbitPen pen = new ChickenRabbitPen(10, 28);
        System.out.println("鸡的数量为:" + pen.getChickenCount());
        System.out.println("兔的数量为:" + pen.getRabbitCount());
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

}

写一个鸡兔同笼的Java

原文地址: https://www.cveoy.top/t/topic/bvK5 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录