一、查看以下代码,你发现什么特殊之处,通过几种方法区分同名方法
1 // MethodOverload.java 2 // Using overloaded methods 3 4 public class MethodOverload { 5 6 public static void main(String[] args) { 7 System.out.println("The square of integer 7 is " + square(7)); 8 System.out.println("\nThe square of double 7.5 is " + square(7.5)); 9 }10 11 public static int square(int x) {12 return x * x;13 }14 15 public static double square(double y) {16 return y * y;17 }18
答: 上面的代码两个方法名相同,但能准确调用
上述示例代码展示了Java的“方法重载(overload)”特性。
满足以下条件的两个或多个方法构成“重载”关系: (1)方法名相同; (2)参数类型不同,参数个数不同,或者是参数类型的顺序不同。(注意:方法的返回值不作为方法重载的判断条件。)二、编写一个方法,使用以下算法生成指定数目(比如1000个)的随机整数
三、组合数(利用阶乘、杨辉三角、递归来实现)
1 import java.io.*; 2 public class CombinatorialNumber { 3 public static void main(String[] args) throws IOException{ 4 BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); 5 String num1 = reader.readLine(); String num2 = reader.readLine(); 6 int n = Integer.parseInt(num1);int k = Integer.parseInt(num2); 7 if(n>=2&&k>1&&(n>=k)) 8 { 9 int sum1,sum2,sum3; 10 sum1 = nStratum(n,k); 11 System.out.println("The combinatorial number of (n,k)is " + sum1); 12 sum2 = triangleYH(n,k);13 System.out.println("The combinatorial number of (n+1,k)is " + sum2);14 sum3 = digui(n,k);15 System.out.println("The combinatorial number of (n,k)is " + sum3); 16 } 17 else if(n>=2&&k==1) 18 {19 System.out.println("The combinatorial number of (n,k)is " + n); 20 } 21 else if(n==1&&k==1) 22 { 23 System.out.println("The combinatorial number of (n,k)is 1."); 24 } 25 else26 { 27 System.out.println("Error!please input again!"); 28 }29 }30 31 public static int nStratum(int n,int k)//阶乘32 { 33 int n_stratum=1,k_stratum=1,n_k_stratum=1,sum=1;34 int i; 35 for(i=1;i<=n;i++) { n_stratum=n_stratum*i; } 36 for(i=1;i<=k;i++) { k_stratum=k_stratum*i; } 37 for(i=1;i<=(n-k);i++) { n_k_stratum=n_k_stratum*i; } 38 sum = n_stratum/(k_stratum*n_k_stratum); 39 return sum;40 } 41 public static int digui(int n,int k)//递归 42 { 43 if(k==1) return n;44 else 45 { 46 int sum = (digui(n,k-1))*(n-1)/k; 47 return sum; 48 } 49 }50 public static int triangleYH(int n,int k)//杨辉三角51 { 52 int sum,sum1,sum2; 53 sum1 = digui(n,k);54 sum2 = digui(n,k-1);55 sum = sum1+sum2;56 return sum; 57 }58 }
四.运用递归判断某个字符串是否回文
//判断字符串是否回文
public class Palindrome {
public static boolean isPalindrome(String s,int i,int j)
{ if(i>j) throw new IllegalArgumentException();
if(i == j) return true;
else{ return (s.charAt(i)==s.charAt(j))&& isPalindrome(s,i+1,j-1); }
}
public static void main(String[] args) {
String test = "123";
int i=0; int j=test.length()-1;
System.out.println(test + " is Palindrome?" + Palindrome.isPalindrome(test, i, j));
}
}