2015-04-03 35 views
0

我在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); 
} 
} 
+0

爲此''(key!= arr [element] && element <= N)'添加一個條件以防止出現界限。像'key Kon 2015-04-03 15:43:35

+0

@Kon我用'element 2015-04-03 15:50:27

回答

0

你的代碼本身具有一些問題,請看看我的修改後的代碼。應該幫助你。

public static void search (int arr[]) { 
    Scanner in = new Scanner(System.in); 
    int key; 
    int N = arr.length; 
    int element = 0; 

    System.out.println("Enter the number that you want to search: "); 
    key = in.nextInt(); 
    boolean found = false; 
    while (element < N) 
    { 
     if(key == arr[element]){ 
      found = true; 
      break; 
     } 
     element++; 
    } 

    if(!found) 
     {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); 
} 
+0

它的工作謝謝你 – 2015-04-03 16:51:08

0

試試這個:

while (element < N && key != arr[element]) 

這不起作用:

while (key != arr[element] && element < N) 

因爲當elements到達的N值這個代碼key != arr[element]仍然會執行,並呼籲arr[arr.length]拋出例外。