简体   繁体   中英

Why can't I return an index of an array as int in Java?

Apparently Eclipse keeps giving me an error asking me to return an int. Is array[i] not considered an int or we cant return an index of a array in java like this? Anyone out there that can help me?

public static void main(String[] args){     
    int[] array = {10,6,4,3,12,19,18};
    int z = quick_find_1d_peak1(array);
    System.out.println(z);
}

public static int quick_find_1d_peak1(int[] inputArray){
    for (int i=0 ; i<inputArray.length ; ){
        if (i==0 && inputArray[i] >= inputArray[i+1]){
            return inputArray[i];
        } else if (i==inputArray.length && inputArray[i] >= inputArray[i-1]){
            return inputArray[i];
        } else if (inputArray[i] >= inputArray[i-1] && inputArray[i] >= inputArray[i+1]){
            return inputArray[i];
        } else {
            i++;
        }
    }
}

In quick_find_1d_peak1 , your last conditional (the else ) doesn't return anything. This means it is possible nothing gets returned ever. To fix this, either return something in the else (which is probably not what you want to do because you're incrementing i to go to the next one), or return something after the for loop so something will get returned no matter what.

You're not guaranteed to return a result. For example, suppose inputArray is empty, then the for loop never gets entered, and nothing is returned. Or if none of the conditions inside the loop ever fire, then your else doesn't return anything.

You have to guarantee that you return something in a method (or throw an exception).

You may want to use a try-catch block or return something if none of your conditions are fullfiled(like default in a switch perhaps).

http://www.dreamincode.net/forums/topic/22661-exception-basics-try-catch-finally/

Hope this helps.

Cheers!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM