方法
方法定义及格式:
方法就是完成特定功能的代码块(函数)
格式:
修饰符 返回值类型 方法名 (参数类型 参数名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 数组类型[][]{{元素....},{元素.....},{元素....}};
数组长度可用:数组名.lenght 表示
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