方法的参数传递机制:只能是值传递
package Collection; public class ZhiCd { //此处如果不加静态static //Exception in thread "main" java.lang.Error: Unresolved compilation problem: // Cannot make a static reference to the non-static method swap(int, int) from the type ZhiCd public static void swap(int a,int b) { int temp; temp = a; a=b; b=temp; System.out.println("swap:"+"a:"+a+" "+"b:"+b); } public static void main(String[] args) { // TODO Auto-generated method stub int a=9; int b=6; swap(a, b); System.out.println("a:"+a+" "+"b:"+b); } }
package Collection; class DataWrap { int a; int b; } public class ReferenceTransferTest { /** * @param dw */ public static void swap(DataWrap dw) { int temp; temp=dw.a; dw.a=dw.b; dw.b=temp; System.out.println("DataWrap方法"+dw.a+" "+dw.b); } public static void main(String[] args) { DataWrap dw=new DataWrap(); // DataWrap dw=null; dw.a=6; dw.b=9; swap(dw); System.out.println("DataWrap方法后"+dw.a+" "+dw.b); } }
递归方法:
例子:
f(0)=1,f(1)=4,f(n+2)=2*f(n+1)+f(n)
package Collection; public class Recursive { public static int fn(int n) { if(n==0) { return 1; } else if(n==1) { return 4; } else { return 2*fn(n-1)+fn(n-2); } } public static void main(String[] args) { // TODO Auto-generated method stub System.out.println(fn(10)); //10497 } }
时间: 2024-10-06 06:00:03