java簡單例項
1、有一對兔子,每三個月生一對兔子,每對小兔子長到三個月之後開始生兔子,問20個月之後一共有多少對兔子(假設沒有兔子死),用遞迴演算法實現。
public class DiGui {
public static void main(String[] args){
int sum=0;
for(int i=1;i<=20;i++){
sum=f(i);
}
System.out.println(sum);
}
public static int f(int n){
if(n==1||n==2){
return 1;
}else{
return f(n-2)+f(n-1);
}
}
}
2、定義一個數組,比如:int[] arr = {13,24,57,69,80}使用二分查詢查詢這個陣列中的24元素對應的索引
public class ErFenChaZhao {
public static void main(String[] args){
int[] src = new int[] {13,24,57,69,80};
System.out.println(binarySearch(src,69));
}
public static int binarySearch(int[] srcArray, int des){
int low = 0;
int high = srcArray.length-1;
while(low <= high) {
int middle = (low + high)/2;
if(des == srcArray[middle]) {
return middle;
}else if(des <srcArray[middle]) {
high = middle - 1;
}else {
low = middle + 1;
}
}
return -1;
}
}
3、統計大串中小串出現的次數
舉例:在字串” woaijavawozhenaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagun”中java出
現了5次
package threehomework;
import java.util.Scanner;
public class XunZhaoZFC {
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
System.out.println("請輸入一行字串:");
String str=sc.nextLine();
int num;
System.out.println("請輸入指定字串:");
String str1=sc.nextLine();
num=tongji(str,str1);
System.out.println("num:"+num);
}
public static int tongji(String strr1,String strr2){
char[] ch1=strr1.toCharArray();
char[] ch2=strr2.toCharArray();
int num1=0;
for(int x=0;x<ch1.length;x++){
if(ch1[x]==ch2[0]){
int a=0;
for(int i=1,j=x+1;i<ch2.length;i++,j++){
if(ch1[j]==ch2[i]){
a++;
x=j-1;
}else break;
}
if(a==ch2.length-1){
num1++;
}
}
}
return num1;
}
}