1.1.2. 数组遍历
public static void main(String[] args) {
int[] x = { 1, 2, 3 };
for (int i = 0; i < 3; i++) {
System.out.println(x[i]);
}
}
数组中有一个属性可以获取到数组中元素的个数,也就是数组的长度. 数组名.length
public static void main(String[] args) {
int[] x = { 1, 2, 3 };
for (int i = 0; i < x.length; i++) {
System.out.println(x[y]);
}
}
1.1.3. 数组的常见异常
一数组角标越界异常:,注意:数组的角标从0开始。
public static void main(String[] args) {
int[] x = { 1, 2, 3 };
System.out.println(x[3]);
//java.lang.ArrayIndexOutOfBoundsException
}
二 空指针异常:
public static void main(String[] args) {
int[] x = { 1, 2, 3 };
x = null;
System.out.println(x[1]);
// java.lang.NullPointerException
}
数组的特点:
数组长度是固定的。
1.1.4. 数组的常见操作
1:定义一个遍历数组的函数
2:定义一个求数组和的功能函数
3:定义一个获取数组最大值的功能函数
4:定义一个获取数组最大值角标的功能函数
5:定义一个返回指定数在指定数组中包含的角标的功能函数
6:定义一个可以用于排序int数组的函数
1:冒泡
2:选择
7:定义一个可以将整数数组进行反序的功能函数。
8:二分查找(必须是有序的 )
基本操作:
1、获取最值(最大值,最小值)
2、排序(选择排序,冒泡排序) //6,2,8,-1,5,9,7
3、折半查找(二分查找)
1.1.4.1. 获取最值
1获取最大值,
2获取最小值,
3使用0进行比较的问题(元素全是负数)。定义第三方变量的问题。
public static int getMax(int[] arr) {
int max = 0;
for (int x = 0; x < arr.length; x++) {
if (max < arr[x]) {
max = arr[x];
}
}
return max;
}
public static void main(String[] args) {
int[] x = new int[] { 2, 5, 6, 20, 100 };
int max=getMax(x);
System.out.println(max);
}
注意:如果数组中有负数(元素全是负数),还可以吗?
所以:初始化为0,正整数没问题如果是负数。那么就初始化为元素的任意一个元素
public static int getMax(int[] arr) {
int max = arr[0];
for (int x = 0; x < arr.length; x++) {
if (max < arr[x]) {
max = arr[x];
}
}
return max;
}
注意:定义变量的时候初始化为0, 其实也是可以的。让变量作为角标就行了。
public static int getMax(int[] arr) {
int max = 0;
for (int x = 0; x < arr.length; x++) {
if (arr[max] < arr[x]) {
max = x;
}
}
return arr[max];
}