递归调用
1. 有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问第二十 个月的兔子对数为多少?(使用递归去解决)
2. public class RobbitDemo01 {
3. public static void main(String[] args) {
4. // TODO自动生成的方法存根
5. int num=Birth(20);
6. System.out.println("20个月后总共有" + num + "对兔子.");
7. }
8. public static int Birth(int month){
9. int result=0;
10. if(month==1 || month==2){
11. result=1;
12. }
13. else if(month==3){
14. result=Birth(month-1)+ Birth(month-2);
15. }
16. else if(month>=4){
17. result=Birth(month-1)+ Birth(month-3);
18. }
19. return result;
20. }
21. }
2.定义一个数组,比如:int[] arr = {13,24,57,69,80}使用二分查找查找这个数组中的24元素对应的索引(可以不写这个题,下去预习什么是二分查找)
老师,这个题不会!!!
3统计大串中小串出现的次数
public class StringCountDemo01 {
public static void main(String[] args) {
// TODO自动生成的方法存根
StringBuffer sb1=new StringBuffer();//创建字符串缓冲区对象
sb1.append("my life is brilliant! oh my baby! mylove! ");//调用StringBuffer的append()方法添加字符串
String Str1=sb1.toString();//将StringBuffer类型转换为String类型
System.out.println("大串为:" + Str1);
String Str="my";//定义小串常量
System.out.println("小串是:" + Str);
SubStringDemo(Str1);
}
public static void SubStringDemo(String s){
int count=0;//定义一个计数器
System.out.print("小串有:");
for(int i=0;i<s.length()-1;i++){
String Str2=s.substring(i, i+2);//在循环中调用subString()方法,按没两位截取
System.out.print(Str2 + ",");
if(Str2.equals("my")){
count++;//调用String的equals()方法,与小串进行对比,如果相等,count加一
}
}
System.out.println(" ");
System.out.print("大串中小串出现的次数是:" + count + "次");
}
}