gpt4 book ai didi

java - While 循环无法正常工作。 ArrayIndexOutOfBoundsException

转载 作者:行者123 更新时间:2023-12-01 23:07:11 25 4
gpt4 key购买 nike

我的 while 循环条件似乎不起作用,我尝试使用 < 和 <= 执行条件,但它仍然不起作用,当我输入无法找到的内容时,会继续出现越界错误。当我输入可以找到的内容时它工作正常,但当无法找到它时,它会出现越界错误

错误信息是这样的

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 20

代码:

public static void main(String[] args) {
int listsize;
int[] listTosearch = new int[20];
int elementTofind;
boolean found = false;
int indexToSearch;
int indexOfelementTofind = -1;

Scanner myScanner = new Scanner(System.in);
System.out.println("Size of list to search?");
listsize = myScanner.nextInt();

for (int i = 0; i <= listsize - 1; i++){
listTosearch[i] = 1 + (int) (Math.random()*(100-1)+1);
System.out.println(listTosearch[i]);

}
System.out.println("Element to find?");
elementTofind = myScanner.nextInt();
indexToSearch = 0;

while (indexToSearch < listsize -1 || found == false){ // This is the line that isn't working
if (listTosearch[indexToSearch] == elementTofind ){
found = true;
indexOfelementTofind = indexToSearch + 1 ;
}
indexToSearch ++;
}

if (found == true){
System.out.println(elementTofind + " is at index " + indexOfelementTofind);
} else {
System.out.println("The element was not found");
}
}

最佳答案

while (indexToSearch < listsize -1 || found == false){

应该是:

while (indexToSearch < listsize -1 && found == false){

或者正如 peter.petrov 指出的那样:

while (indexToSearch < listsize && !found)

实际搜索整个数组。

<小时/>

您还可以考虑通过更改以下内容来提高代码的可读性:

for (int i = 0; i <= listsize - 1; i++){

for (int i = 0; i < listsize; i++){
<小时/>

这也有点奇怪:

    if (listTosearch[indexToSearch] == elementTofind ){
found = true;
indexOfelementTofind = indexToSearch + 1 ;
}

并造成误导:

System.out.println(elementTofind + " is at index " + indexOfelementTofind);

因为找到的元素位于索引 indexToSearch 处,而不是 indexToSearch + 1

<小时/>
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);

System.out.println("Size of list to search?");
int listSize = myScanner.nextInt();

int[] listToSearch = new int[listSize];
for (int i = 0; i < listSize; i++) {
listToSearch[i] = 1 + (int) (Math.random()*(100-1)+1);
System.out.println(listToSearch[i]);
}

System.out.println("Element to find?");
int elementToFind = myScanner.nextInt();

int index = 0;
boolean found = false;
while (index < listSize && !found) {
if (listToSearch[index] == elementToFind) {
found = true;
} else {
index++;
}
}

if (found) {
System.out.println(elementToFind + " is at index " + index);
} else {
System.out.println("The element was not found");
}
}

关于java - While 循环无法正常工作。 ArrayIndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22589971/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com