Java logic error in returning array position using while/if statements

Refresh

April 2019

Views

59 time

1

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 :)

2 answers

2

Your loop only runs when database[i] != item, this is true for index 0 (the very first iteration). The next statement is ++i which makes i 1. Then you check if i < database.length, which is true when i is 1.

You probably want to put the if / else after your loop. That way if it finishes before it runs out of elements (i.e. if i < database.length) you've found it. Otherwise you didn't find it.

-1

You are not comparing correctly your item, and you are not checking all the array.

Try this:

public class Ejemplo {

static int [] database = {17,18,19,20,21};

public static int findItem(int item) {
    for( int i=0; i < database.length; i++ ) {
        if ( database[i] == item ) {
            System.out.println("Item found at position: " + i);
            return i;
        } 
    }
    System.out.println("Item not found.");
    return -1;
}

public static void main(String [] args) {
        findItem(20);
}

}