面向对象程序设计03

利用方法重载实现鸡兔同笼

import java.util.Scanner;

public class Main {
    static Scanner input = new Scanner(System.in);
    public static void main(String[] args) {
        System.out.print("请依次输入脚的数量和头的数量:");
        int foot = 0;
        int head = 0;
        solu(foot,head);
        solu();
    }
    public static void solu(int foot1, int head1){
        do {
            foot1 = input.nextInt();
            head1 = input.nextInt();
            int rabbits = (foot1 - (head1 * 2)) / 2;
            int chickens = head1 - rabbits;

            if (2 * chickens + 4 * rabbits == foot1) {
                System.out.println("兔子的只数为:" + rabbits);
                System.out.println("鸡的只数为:" + chickens);
            } else
                System.out.println("数据不合法");
            System.out.println("请依次输入脚的数量和头的数量:(输入脚的数量为0时,终止程序)");

        } while (foot1 != 0);
    }

    public static void solu(){
        System.out.println("(只计算一次)");
        int foot = input.nextInt();
        int head = input.nextInt();
        int rabbits = (foot - (head * 2)) / 2;
        int chickens = head - rabbits;

        if (2 * chickens + 4 * rabbits == foot) {
            System.out.println("兔子的只数为:" + rabbits);
            System.out.println("鸡的只数为:" + chickens);
        } else
            System.out.println("数据不合法");
        System.out.print("请依次输入脚的数量和头的数量:(输入脚的数量为0时,终止程序)");
    }

}

评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注