不说废话,贴代码
/** * 鸡兔同笼问题:穷举算法思想 */import java.util.*;public class ChichenAndHabbit { static int chichenNum,habbitNum; public static void main(String[] args) { int head,foot; boolean flag; System.out.println("穷举算法求解鸡兔同笼问题"); System.out.println("请输入头数:"); Scanner input = new Scanner(System.in); head = input.nextInt(); System.out.println("请输入脚的数目?"); foot = input.nextInt(); flag = exhaustAgm(head,foot); if (flag == true ) { System.out.print("鸡有"+chichenNum+"只,兔有"+habbitNum+"只。"); }else { System.out.print("无法求解"); } } public static boolean exhaustAgm(int head, int foot){ boolean flag = false; for (int i = 0; i <= head; i++) { int j = head - i; if (i*2+j*4 == foot) {//判段,如果找到答案 flag = true; chichenNum = i; habbitNum = j; } } return flag; } }