【问题标题】:Sequential Search array out of bound issue in javajava中的顺序搜索数组越界问题
【发布时间】:2015-04-03 15:41:54
【问题描述】:

我在 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] &amp;&amp; element &lt;= N) 添加一个条件以防止越界。类似key &lt; N
  • @Kon 我同时使用了element &lt; N element &lt;= N 他们都没有工作。

标签: java arrays algorithm search sequential


【解决方案1】:

您的代码本身没有什么问题,请查看我修改后的代码。应该能帮到你。

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);
}

【讨论】:

    【解决方案2】:

    试试这个:

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

    这不起作用:

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

    因为当elements 得到N 的值时,这段代码key != arr[element] 仍将被执行,调用arr[arr.length] 会引发异常。

    【讨论】:

      猜你喜欢
      • 2014-04-27
      • 1970-01-01
      • 2014-03-04
      • 2015-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多