如何解决为什么我的使用“for-each 循环”的线性搜索代码不适用于混合输入?
我的代码适用于 11,12,13,14,15
等升序或降序数组输入......但它不适用于 11 13 12 15 14
等混合顺序数组输入。
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");
}
}
}
解决方法
我认为问题出在这里: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
而不是 100
初始化数组:
int LS[] = new int[n];
当你初始化数组时,它会根据大小分配内存。想想n
等于20
,那么初始化数组大小为100
否则,如果用户输入的值大于 100,程序将抛出 ArrayIndexOutOfBoundsException
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。