06方法&数组


方法&数组


1、方法

(1)结构
修饰符 返回值类型 方法名(参数列表){
方法体
}
eg:public static int getMin(int a,int b){
int min = a>b?b:a;
return min;
}
注:参数列表:参数类型,参数个数,参数顺序
(2)调用方法
①类名.方法名();
调用方法和被调用方法必须使用static修饰;
②方法名();
1)调用方法和被调用方法必须处于同一个类中;
2)调用方法和被调用方法必须都有或都没有static修饰;
③对象名.方法名();
通过实例化的对象,再调用对象的方法;
(3)返回值类型
①基本数据类型
②应用数据类型
③void:
注:使用void做返回值类型是,表示此方法没有返回值,不能将该方法放在打印语句中。
有返回值类型的方法时,返回的数据的数据类型必须与定义方法是指定的数据类型一致;
有返回值时,需要使用return关键字对结果进行返回。

(4)方法重载
完全相同的方法名,不同的参数列表(参数个数,参数类型,参数顺序)
①方法签名:方法名+参数列表(参数类型,参数个数,参数顺序)
(5)用法
①直接在打印输出语句中输出(必须要有返回值)
②参与运算
③作为参数传递
④为变量赋值(接收数据的变量类型必须与返回值类型一致)

2、数组

(1)声明
①静态创建:
1)结构:
① 数据类型[] 数组名 = new 数组类型[]{参数1,参数2,…,参数n};
② 数据结构[] 数组名 = {参数1,参数2,…,参数n};
eg: ① int[] arr = new int[]{1,2,3,4};
②int[] arr = {1,2,3,4};
②动态创建
1)结构:
① 数据类型[] 数组名 = new 数据类型[数组长度];
② 数据类型[] 数组名;
数组名 = new 数据类型[数组长度];
eg: ① int[] arr = new int[3];
② int[] arr;
arr = new int[4];
(2)使用元素:
数组名[元素下标];
数组元素:数组中存放的每一个值
下标(索引):元素在数组中的位置,从0开始,长度-1结束。
数组长度:指数组中存放元素的个数,可使用 数组名.length;获得数组长度。
(3)注意

3、二维数组

(1)声明
①动态声明
数据类型[] [] 数组名 = new 数据类型[长度][长度];
eg:int[] [] arr = new int[3][4];
②静态声明
数据类型[][] 数组名 = new int[][]{数组1,数组2,数组3,…,数组n};
数据类型[][] 数组名 = {数组1,数组2,数组3,…,数组n};

eg: int[][] arr = new int[][]{{1,2,3},{5,4},{10,1,20,85}};
int[][] arr = {{1,2,3},{5,4},{10,1,20,85}};

4、数组遍历

(1)一维数组
int[] arr = new int[]{1,2,3,4};
for(int i = 0;i < arr.length;i++){
System.out.println(arr[i]);
}
(2)二维数组
int[][] arr = new int[][]{{1,2,3},{5,4},{10,1,20,85}};
for(int i = 0;i < arr.length;i ++){
for(int j = 0;j< arr[i].length;j ++){
System.out.println(arr[i][j]);
}
}

猜你喜欢

转载自blog.csdn.net/weixin_43842554/article/details/89874705