虽然循环不能正常工作。 ArrayIndexOutOfBoundsException异常

时间:2014-03-23 11:02:11

标签: java while-loop conditional-statements indexoutofboundsexception

我的while循环条件似乎不起作用,我尝试用<并且< =当我输入无法找到的东西时,它仍然没有工作继续给我一个outofbounds错误。当我输入可以找到的东西时它工作正常但是当它无法找到时会发生异常错误

错误信息是这个

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");
    }
}

1 个答案:

答案 0 :(得分:3)

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");
  }
}