我的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/

10-13 08:46