public class MethodOverload { public static void main(String[] args) { System.out.println("The square of integer 7 is " + square(7)); System.out.println(" The square of double 7.5 is " + square(7.5)); } public static int square(int x) { return x * x; } public static double square(double y) { return y * y; } }
两个函数均为square命名,只是类型不同但结果不同。
这一段代码展示了Java的“方法重载(overload)”特性。
满足以下条件的两个或多个方法构成“重载”关系:
(1)方法名相同。
(2)参数类型不同,参数个数不同,或者是参数类型的顺序不同。
杨辉三角:
package dome; import java.util.Arrays; public class shuzu { public static void main(String[]args){ int a[][] = new int[4][4]; //建立4 4 的二维数组 for(int i=0;i<4;i++) { for(int j=0;j<=i;j++) { if(j==0) a[i][j]=1; //根据原则令第一列和对角线的值赋为1 else if(i==j) a[i][j]=1; } } for(int m=2;m<4;m++) { for(int n=1;n<=m-1;n++) a[m][n]=a[m-1][n]+a[m-1][n-1]; //杨辉三角核心 } for(int i=0;i<4;i++) { for(int j=0;j<=i;j++) { System.out.print(a[i][j]+" "); } System.out.println(); } } }
汉诺塔程序测试:
package dome; public class TowersOfHanoi { // recursively move disks between towers递归移动塔之间的磁盘 public static void solveTowers( int disks, int sourcePeg, int destinationPeg, int tempPeg ) { // base case -- only one disk to move基本情况-只有一个磁盘移动 if ( disks == 1 ) { System.out.printf( " %d --> %d", sourcePeg, destinationPeg ); return; } // end if // recursion step -- move (disk - 1) disks from sourcePeg // to tempPeg using destinationPeg solveTowers( disks - 1, sourcePeg, tempPeg, destinationPeg ); // move last disk from sourcePeg to destinationPeg System.out.printf( " %d --> %d", sourcePeg, destinationPeg ); // move ( disks - 1 ) disks from tempPeg to destinationPeg solveTowers( disks - 1, tempPeg, destinationPeg, sourcePeg ); } // end method solveTowers public static void main( String[] args ) { int startPeg = 1; // value 1 used to indicate startPeg in output int endPeg = 3; // value 3 used to indicate endPeg in output int tempPeg = 2; // value 2 used to indicate tempPeg in output int totalDisks = 3; // number of disks // initial nonrecursive call: move all disks. solveTowers( totalDisks, startPeg, endPeg, tempPeg ); } // end main } // end class TowersOfHanoi
使用递归方式判断某个字串是否是回文:
package dome; import java.util.Scanner; public class Palindrome { public static void main(String[] args){ System.out.println("请输入字符"); Scanner s=new Scanner(System.in); //输入一个字符串 String str=null; str=s.next(); int i = 0; int j = str.length() - 1; System.out.println(str + " 回文吗?" +isPalindrome(str, i, j)); } public static boolean isPalindrome(String s,int i,int j){ if(i > j) return false; if(i == j) return true; else{ return (s.charAt(i) == s.charAt(j)) && isPalindrome(s,i+1,j-1); } } }