/*
數組操作的兩個常見小問題:
ArrayIndexOutOfBoundsException:數組索引越界異常
原因:你訪問了不存在的索引。
NullPointerException:空指針異常
原因:數組已經不在指向堆內存了。而你還用數組名去訪問元素。
作用:請自己把所有的場景Exception結尾的問題總結一下。以后遇到就記錄下來。
現象,原因,解決方案。
*/
class ArrayDemo6 {
public static void main(String[] args) {
//定義數組
int[] arr = {1,2,3};
//System.out.println(arr[3]);
//引用類型的常量:空常量 null
arr = null;
System.out.println(arr[0]);
}
}
數組操作的兩個常見小問題:
檢查數組中一個數出現過幾次。
需求:數組元素查找(查找指定元素第一次在數組中出現的索引)
分析:
A:定義一個數組,並靜態初始化。
B:寫一個功能實現
遍歷數組,依次獲取數組中的每一個元素,和已知的數據進行比較
如果相等,就返回當前的索引值。
*/
class ArrayTest5 {
public static void main(String[] args) {
//定義一個數組,並靜態初始化
int[] arr = {200,250,38,888,444};
//需求:我要查找250在這個數組中第一次出現的索引
int index = getIndex(arr,250);
System.out.println("250在數組中第一次出現的索引是:"+index);
int index2 = getIndex2(arr,250);
System.out.println("250在數組中第一次出現的索引是:"+index2);
int index3 = getIndex2(arr,2500);
System.out.println("2500在數組中第一次出現的索引是:"+index3);
}
/*
需求:查找指定數據在數組中第一次出現的索引
兩個明確:
返回值類型:int
參數列表:int[] arr,int value
*/
public static int getIndex(int[] arr,int value) {
//遍歷數組,依次獲取數組中的每一個元素,和已知的數據進行比較
for(int x=0; x<arr.length; x++) {
if(arr[x] == value) {
//如果相等,就返回當前的索引值。
return x;
}
}
//目前的代碼有一個小問題
//就是假如我要查找的數據在數組中不存在,那就找不到,找不到,你就對應的返回嗎?
//所以報錯。
//只要是判斷,就可能是false,所以大家要細心。
//如果找不到數據,我們一般返回一個負數即可,而且是返回-1
return -1;
}
public static int getIndex2(int[] arr,int value) {
//定義一個索引
int index = -1;
//有就修改索引值
for(int x=0; x<arr.length; x++) {
if(arr[x] == value) {
index = x;
break;
}
}
//返回index
return index;
}
}