本节内容视频链接:https://www.bilibili.com/video/BV12J41137hu?p=55&vd_source=b5775c3a4ea16a5306db9c7c1c1486b5https://www.bilibili.com/video/BV12J41137hu?p=55&vd_source=b5775c3a4ea16a5306db9c7c1c1486b5
1.数组边界
- 数组下标的合法区间[ 0, Length-1],如果越界就会报错:ArrayIndexOutOfBoundsException
2.打印全部的数组元素
public class ArrayDemo02 {
public static void main(String[] args) {
int[] arrays = {1, 2, 3, 4, 5, 6, 7, 8};
//打印全部的数组元素
for (int i = 0; i < arrays.length; i++){
System.out.println(arrays[i]);
}
3.计算数组元素的和
public class ArrayDemo02 {
public static void main(String[] args) {
int[] arrays = {1, 2, 3, 4, 5, 6, 7, 8};
//计算所有元素的和
int sum = 0;
for (int i = 0; i < arrays.length; i++){
sum+=arrays[i];
}
System.out.println(sum);
}
}
4.查找数组中的最大元素
public static void main(String[] args) {
int[] arrays = {1, 2, 3, 4, 5, 6, 7, 8};
//查找数组中的最大元素
int max = arrays[0];
for (int i = 1; i < arrays.length ; i++) {
if (arrays[i] > max){
max = arrays[i];
}
}
System.out.println("max=" + max);
}
}
5.使用For-Each遍历数组
public class ArrayDemo02 {
public static void main(String[] args) {
int[] arrays = {1, 2, 3, 4, 5, 6, 7, 8};
for (int array : arrays) {
System.out.println(array);
}
}
}
6.数组作为方法入参
public class ArrayDemo02 {
public static void main(String[] args) {
int[] arrays = {1, 2, 3, 4, 5, 6, 7, 8};
printArray(arrays);
}
//自己写一个打印数组元素的方法
public static void printArray(int[] arrays){
for (int array : arrays) {
System.out.print(array + " ");
}
}
}
7.数组作为返回值
public class ArrayDemo02 {
public static void main(String[] args) {
int[] arrays = {1, 2, 3, 4, 5, 6, 7, 8};
// printArray(arrays);
int[] reverse = reverse(arrays);
printArray(reverse);
}
//自己写一个打印数组元素的方法
public static void printArray(int[] arrays){
for (int array : arrays) {
System.out.print(array + " ");
}
}
public static int[] reverse(int[] arrays){
int[] result = new int[arrays.length];
for (int i = 0, j = arrays.length-1; i < arrays.length; i++, j--) {
result[j] = arrays[i];
}
return result;
}
}