1

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++;
        }
    }
}
1
  • 1
    Not directly related to you question, but the condition in the first else clause will never be true, so the code there will never be executed. (Should it read i==inputArray.length-1 && ... instead?) Commented Oct 7, 2014 at 16:25

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

0

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.