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

喜你入骨 提交于 2019-12-11 06:53:14

问题


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


回答1:


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.




回答2:


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);
}

}



来源:https://stackoverflow.com/questions/46385470/java-logic-error-in-returning-array-position-using-while-if-statements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!