- 克隆对象
public class Copy { public static void main(String[] args) { person p =new person(); p.name ="小明"; p.age=10; myTools tool =new myTools(); person p2=tool.copyPerson(p); System.out.println(p.name+"\t"+p.age); System.out.println(p2.name+"\t"+p2.age); } } class person{ String name; int age; } class myTools{ public person copyPerson(person p){ person p2 = new person(); p2.name =p.name; p2.age = p.age; return p; }
- 阶乘
//阶乘 public class factorial { public static void main(String[] args) { Test t1 =new Test(); int res = t1.ffactorial(6); System.out.println(res); } } class Test{ public int ffactorial(int n){ if(n==1){ return 1; }else{ return ffactorial(n-1)*n; } } }
- 斐波那契数列
public class fibonaqi { public static void main(String[] args) { int n=-1; A t1 =new A(); int res= t1.fibonacci(7); if(res != -1){ System.out.println(res); }else{ System.out.println("错误!!!!!"); } } } class A{ public int fibonacci(int n){ if(n>=1){ if(n==1||n==2){ return 1; }else{ return (fibonacci(n-1) + fibonacci(n-2)); } }else{ System.out.println("输入的数字有误"); return -1; } } }
- 用二维数组创建迷宫
public class maze { public static void main(String[] args) { /*思路 * 1、先创迷宫,用二维数组表示int[][] map = new int[8][7]; * 2、先规定map数组的元素值,0表示可以走,1表示障碍物 * */ int[][] map = new int[8][7]; //3、将四周的值全部设为1 for(int i=0;i<map.length;i++){ for(int j=0;j<map[i].length;j++){ map[i][0]=1; map[i][map[i].length-1]=1; map[0][j]=1; map[map.length-1][j]=1; } } map[2][1]=1; map[2][2]=1; //输出当前地图 System.out.println("=========地图========"); for(int i=0;i<map.length;i++){//遍历数组 for(int j=0;j<map[i].length;j++){ System.out.print(map[i][j]+" "); } System.out.println(); } //使用findway找路 AA a=new AA(); a.findway(map, 1, 1);//调用findway方法 System.out.println("============路线========"); for(int i=0;i<map.length;i++){//遍历新数组 for(int j=0;j<map[i].length;j++){ System.out.print(map[i][j]+" "); } System.out.println(); } } } class AA{ public boolean findway(int[][] map,int i,int j){ if(map[6][5]==2){ return true; }else{ if(map[i][j]==0){ map[i][j]=2;//假定可以走通 if(findway(map,i+1,j)){//向下移动 return true; }else if(findway(map,i,j+1)){//向右移动 return true; }else if(findway(map,i-1,j)){//向上移动 return true; }else if(findway(map,i,j-1)){//向左移动 return true; }else{ map[i][j]=3; return false; } } } return false; } }
-
猴子偷桃
public class monkePeach { /*一只猴子每天都去偷桃,偷的数量是所有桃的一半还多一个, * 第十天去的时候发现只剩1个桃子了,问第n天的时候剩多少桃子 * */ public static void main(String[] args) { BB b1 =new BB(); int res = b1.monkey(11); if(res != -1){ System.out.println(res); }else{ System.out.println("您输入的天数不对"); } } } class BB{ public int monkey(int n){ if(n==10){ return 1; }else if(n<10){ return (monkey(n+1)+1)*2; }else{ return -1; } } }