Java 为什么我的线性搜索代码使用;“对于每个循环”;不适用于混合输入?
我的代码适用于升序或降序数组输入,如Java 为什么我的线性搜索代码使用;“对于每个循环”;不适用于混合输入?,java,arrays,foreach,linear-search,Java,Arrays,Foreach,Linear Search,我的代码适用于升序或降序数组输入,如11,12,13,14,15等,但不适用于混合顺序数组输入,如11 13 12 15 import java.util.Scanner; public class LinearSearch { public static void main(String[] args) { int LS[]=new int[100]; //LS is the array int n,key,fl
11,12,13,14,15
等,但不适用于混合顺序数组输入,如11 13 12 15
import java.util.Scanner;
public class LinearSearch {
public static void main(String[] args) {
int LS[]=new int[100]; //LS is the array
int n,key,flag=0; //n is the number of array elements and key is the element to be searched
Scanner sc=new Scanner(System.in);
System.out.println("Enter no.of array elements");
n=sc.nextInt();
System.out.println("Enter array elements");
for(int i=0;i<n;i++)
LS[i]=sc.nextInt();
System.out.println("Enter element to search");
key=sc.nextInt();
for (int i:LS){
if(LS[i]==key){
flag=1;
System.out.println(key+" is found at location "+(i+1));
}
}
if(flag==0){
System.out.println(key+" is not found");
}
}
}
import java.util.Scanner;
公共类线性搜索{
公共静态void main(字符串[]args){
int LS[]=new int[100];//LS是数组
int n,key,flag=0;//n是数组元素数,key是要搜索的元素
扫描仪sc=新的扫描仪(System.in);
System.out.println(“输入数组元素的编号”);
n=sc.nextInt();
System.out.println(“输入数组元素”);
for(int i=0;i我认为问题在这里:if(LS[i]==key)
您需要更改为if(i==key)
,因为根据for循环for(int i:LS)
i
表示数组的元素,而不是索引
如果要获取元素的索引,可以使用for
循环而不是foreach
循环:
for(int i = 0; i<LS.length; i++) {
if(LS[i]==key){
flag=1;
System.out.println(key+" is found at location "+(i+1));
}
}
初始化数组时,它会根据大小分配内存。如果n
等于20
,则使用大小100
初始化数组将是一种浪费
否则,如果用户输入的值大于100,程序将抛出
ArrayIndexOutOfBoundsException
我认为问题在于:if(LS[I]==key)
您需要更改为if(I==key)
,因为根据for循环,I代表数组的元素,而不是索引。
int LS[] = new int[n];