Java 基础编程50题——题1
题目1(古典问题):有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第3个月后每个月又生一对兔子, 假如兔子都一直不死,问每个月的兔子有多少对?
解题思想
java源代码
package _01_rabbit_problen;
import java.util.Scanner;
/*
* 题目(古典问题):有一对兔子,从出生后第3个月起每个月都生一对兔子,
* 小兔子长到第3个月后每个月又生一对兔子,
* 假如兔子都一直不死,问每个月的兔子有多少对?
*/
public class Host {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);//创建键盘录入对象
System.out.println("请输入月份:");
while(true) {
try {
int month = sc.nextInt();//接受键盘录入月份
if(Function.rabNum(month) == 0) {
System.out.println("您输入月份应为大于0的整数,请重新输入:");
continue;
}else {
System.out.println("第"+month+"个月有"+Function.rabNum(month)+"对兔子。");
break;
}
} catch (Exception e) {
//e.printStackTrace();
System.out.println("您输入月份应为整数!");
break;
}
}
sc.close();
}
}
package _01_rabbit_problen;
public class Function {
/*
* 函数功能:返回指定月份的兔子的对数
* 思想:递归调用
*/
public static int rabNum(int month) {
if(month <= 0) {
return 0;
}
else if(month == 1 || month == 2) {
return 1;
}else {
return rabNum(month - 1) + rabNum(month - 2);
}
}
}