方法
方法定義及格式:
方法就是完成特定功能的代碼塊(函數)
格式:
修飾符 返回值類型 方法名 (參數類型 參數名1,參數類型 參數名2.....){
函數體;
return 返回值;
}
方法重載:
在同一個類中,允許存在一個以上的同名方法,只要他們的參數個數或者參數類型不同即可。
特點:
與返回值類型無關,只看方法名和參數列表
在調用時,虛擬機通過參數列表的不同來區分同名方法
import java.util.Scanner;
public class Ffcz {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a=sc.nextInt();
int b=sc.nextInt();
System.out.println(sum(a,b));
int c=sc.nextInt();
System.out.println(sum(a,b,c));
double x=sc.nextDouble();
double y=sc.nextDouble();
System.out.println(sum(x,y));
}
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 double sum(double a,double b){
return a+b;
}
}
結果:
5 6
11
7
18
5.1 5.6
10.7
數組
數組的定義格式:
1:數據類型 []數組名;
2:數據類型 數組名[];
數組的初始化:
動態初始化:
格式:數據類型 []數組名 = new 數據類型 [數組長度];
靜態初始化:
格式:數據類型 []數組名 = new 數據類型 []{元素1,元素2......};
數據類型 []數組名 = {元素1,元素2......};
二維數組:
格式1:數據類型 [][]數組名 = new 數據類型[n][m];
格式2:數據類型 [][]數組名 = new 數組類型[][]{{元素....},{元素.....},{元素....}};
import java.util.Scanner;
public class Yhsj {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
show(n);
}
public static void show(int n) {
int [][]a = new int [110][110];
for(int i=1;i<=n;i++) {
for(int j=1;j<=i;j++) {
if(i==j||j==1)
a[i][j]=1;
else
a[i][j]=a[i-1][j-1]+a[i-1][j];
System.out.print(a[i][j]+" ");
}
System.out.println();
}
}
}
結果:
10
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1