I'm new to Java and would appreciate some help in understanding why I'm getting a logic error.
The program searches for "item" in the array "database". The point of the code is to illustrate the use of While and If statements.
The output reads "Item found at position: 1" when it should read "Item found at position: 3"
The code:
class Item {
static int [] database = {17,18,19,20,21};
public static int findItem(int item) {
int i = 0;
while ( i < database.length && database[i] != item ) {
++i;
if ( i < database.length ) {
System.out.println("Item found at position: " + i);
return i;
} else {
System.out.println("Item not found.");
return -1;
}
}
return i;
}
public static void main(String [] args) {
findItem(20);
}}
Thanks :)