我在java中實現了順序搜索。但是,我面臨數組索引超出限制的異常問題。java中的順序搜索數組出界問題
當我輸入正確的數字時,程序工作正常。但是,當我按下一個號碼是不是在陣列內,該程序崩潰,因爲「ArrayIndexOutOfBoundsException異常」
public class Sequential {
public static void search (int arr[]) {
Scanner in = new Scanner(System.in);
int key;
int N = arr.length;
int element = 0;
System.out.prinln("Enter the number that you want to search: ");
key = in.nextInt();
while (key != arr[element] && element <= N)
{
element++;
}
if(element > N)
{System.out.println("not found, try again...");}
else
{System.out.println("found, it's in index # " + element);}
}
public static void main (String[]args)
{
int arr[] = { 2, 3, 4, 5, 7, 11, 34, 37, 77 };
search(arr);
}
}
爲此''(key!= arr [element] && element <= N)'添加一個條件以防止出現界限。像'key
Kon
2015-04-03 15:43:35
@Kon我用'element
2015-04-03 15:50:27