mercredi 27 septembre 2017

Java redundant second if statement in for loop

I'm new to java and inspired by this discussion I wrote a while loop version here and a for loop version (this question) of a program that searches an array for an "item" (int 20, as called in the main method) and returns its value, and they both work.

However, in this for loop version the second if statement, especially "database[i] == database[database.length-1]", looks redundant because the termination condition in the for loop already specifies that i < database.length.

class For {

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;
        }
        if ( database[i] == database[database.length-1] && database[i] != item )
            System.out.println("Item not found.");
    }
    return item;
}

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

I tried swapping the second if with an else statement but then the for loop evaluated every value in the array before 20 and printed "Item not found" three times.

Is this an acceptable use of a for loop and if statements or is it completely redundant?

Aucun commentaire:

Enregistrer un commentaire