不死神兔的處理_演算法剖析

來源:互聯網
上載者:User
package com.it;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;


/*
 * 不死神兔:
 * 題目:
 * 古典問題:有一對兔子,從出生後第3個月起每個月都生一對兔子,小兔子長到第四個月後每個月又生一對兔子,
 * 假如兔子都不死,問每個月的兔子總數為多少?
 * 
 * 需求分析:
 * 第一個月, 1對兔子   2個兔子
 * 第二個月, 1對兔子   2個兔子
 * 第三個月, 2對兔子   4個兔子
 * 第四個月, 3對兔子   6個兔子
 * 第五個月, 5對兔子   10個兔子
 * 第六個月, 8對兔子   16個兔子
 *    .      .     .
 */


public class AthanasiaRabbit {
public static void main(String[] args) throws ParseException {
//鍵盤錄入輸入的開始年月和結束的年月
//static InputStream in,被static修飾的欄位,可以使用類名System直接調用
Scanner sc = new Scanner(System.in);
System.out.println("請輸入開始的年月(yyyy-MM):");
String startDate = sc.nextLine();
System.out.println("請輸入結束的年月(yyyy-MM):");
String endDate = sc.nextLine();
//建立日期格式限定:SimpleDateFormat(String pattern),y  年 ,M  年中的月份  
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
//異常處理
try {
//進行日期格式限定,父類DateFormat:Date parse(String source)
Date startDate1 = sdf.parse(startDate);
Date endDate1 = sdf.parse(endDate);
//日期轉換為字串,父類DateFormat:String format(Date date) 
String startDate2 = sdf.format(startDate1);
String endDate2 = sdf.format(endDate1);
//String[] split(String regex) 
String[] startSplit = startDate2.split("-");
String[] endSplit = endDate2.split("-");
//擷取每一個元素
String startYear = startSplit[0];
String startMonth = startSplit[1];
String endYear = endSplit[0];
String endMonth = endSplit[1];
//把String類型轉為int類型,Integer:static int parseInt(String s) 
int startYear1 = Integer.parseInt(startYear);
int startMonth1 = Integer.parseInt(startMonth);
int endYear1 = Integer.parseInt(endYear);
int endMonth1 = Integer.parseInt(endMonth);
int month = (endYear1-startYear1)*12+(endMonth1-startMonth1);
if (month<0) {
System.out.println("您輸入的資料有誤,請重新輸入!");
} else {
int rabbitNum = getRabbitNum(month);
System.out.println("兔子的總數為:"+rabbitNum*2+"個");
}
} catch (ParseException e) {
System.out.println("您輸入的資料有誤,請按照正確的格式(yyyy-MM)輸出!");
}
}
//使用遞迴方法求兔子數量
public static int getRabbitNum(int month) {
//遞迴的出口
if (month==0||month==1||month==2) {
return 1;
} else {
//方法的內部調用方法本身
return getRabbitNum(month-1)+getRabbitNum(month-2);
}
}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.