java 中的顺序搜索数组越界问题
Sequential Search array out of bound issue in 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);
}
}
您的代码本身没有什么问题,请看我修改后的代码。应该能帮到你。
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);
}
试试这个:
while (element < N && key != arr[element] )
这不起作用:
while (key != arr[element] && element < N )
因为当elements
达到N
的值时,这段代码key != arr[element]
仍然会被执行,调用arr[arr.length]
会抛出异常。
我在 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);
}
}
您的代码本身没有什么问题,请看我修改后的代码。应该能帮到你。
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);
}
试试这个:
while (element < N && key != arr[element] )
这不起作用:
while (key != arr[element] && element < N )
因为当elements
达到N
的值时,这段代码key != arr[element]
仍然会被执行,调用arr[arr.length]
会抛出异常。