My while loop conditions doesn't seem to be working, i tried doing the condition with < and <= and it still doesn't work keeps on giving me the outofbounds error when i enter something that cannot be found. It works fine when I enter something that can be found but when it can't be found it goes to an outofbounds error
the error message is this
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 20
Code:
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");
}
}