T1:杨辉三角
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
print(create(n));
}
public static void print(int [][]arr){
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
public static int[][] create(int n){
int [][]arr=new int[n][];
for (int i = 0; i < n; i++) {
arr[i]=new int[i+1];
arr[i][0]=1;
arr[i][i]=1;
for(int j=1;j<i;j++){
arr[i][j]=arr[i-1][j-1]+arr[i-1][j];
}
}
return arr;
}
}
T2:利用方法重载的特性,实现方法内可传入两个数或三个数或四个数的和
public class Main {
public static void main(String[] args) {
System.out.println(sum(1,2));
System.out.println(sum(1,2,3));
System.out.println(sum(1,2,3,4));
}
public static int sum(int a, int b){
return a+b;
}
public static int sum(int a, int b,int c){
return a+b+c;
}
public static int sum(int a, int b,int c,int d){
return a+b+c+d;
}
T3:利用可变参数列表的特性,实现方法内n个数的和
public class Main {
public static void main(String[] args) {
System.out.println(sum(1,2));
System.out.println(sum(1,2,3));
System.out.println(sum(1,2,3,4));
System.out.println(sum(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20));
}
public static int sum(int ...x){
int sum=0;
for(int i=0;i<x.length;i++){
sum+=x[i];
}
return sum;
}
}