java经典问题——兔子
题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少? 1.程序分析: 兔子的规律为数列1,1,2,3,5,8,13,21....
希望能够详细分析一下您写的代码,我刚刚学习,还有很多不懂,谢谢哒。
程序代码:import javax.swing.JOptionPane;
public class Fibonacci
{
public static void main(String[] args)
{
String res="";
try
{
int month=Integer.parseInt(JOptionPane.showInputDialog(null,"请输入月份上限(>2)","请输入",JOptionPane.INFORMATION_MESSAGE));
int[] fib=new int[month];
fib[0]=fib[1]=1;
for(int i = 2; i < month; i++)
fib[i] = fib[i-1] + fib[i-2];
for(int i = 0; i < month; i++)
res+=(i+1)+"月兔子总数:"+fib[i]+"\n";
JOptionPane.showMessageDialog(null, res, "计算结果",JOptionPane.PLAIN_MESSAGE);
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,e.getMessage(),"错误",JOptionPane.ERROR_MESSAGE);
}
}
}

