Reputation: 421
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");
}
}
Upvotes: 0
Views: 143
Reputation: 39287
while (indexToSearch < listsize -1 || found == false){
should be:
while (indexToSearch < listsize -1 && found == false){
or as peter.petrov pointed out:
while (indexToSearch < listsize && !found)
to actually search your entire array.
You might also consider making your code more readable by changing:
for (int i = 0; i <= listsize - 1; i++){
to
for (int i = 0; i < listsize; i++){
This is also somewhat strange:
if (listTosearch[indexToSearch] == elementTofind ){
found = true;
indexOfelementTofind = indexToSearch + 1 ;
}
and makes this misleading:
System.out.println(elementTofind + " is at index " + indexOfelementTofind);
since the element was found is at index indexToSearch
not 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");
}
}
Upvotes: 3