Home > Enterprise >  error while returning a value from a for-if loop in java
error while returning a value from a for-if loop in java

Time:12-18

your code

Even though you have the return inside the IF statement and the ELSE statement, they will only be reached only IF the code gets inside the FOR statement.

What would happen if you call your method with an empty nums array? if would skip the for statement and there is NOTHING to return for your method in this case, do you get it?

That's why you need a return outside the for/loop as well, meaning that: What your method wants to return if reaches this point?.

If it is a search, for example, you could return -1 outside the FOR/Loop and remove the ELSE statement from inside.

Don't wanna change to much your code, so you clearly see the difference, since you are clearly starting:

public int search(int[] nums, int target) {
    int i;
    int j;
    int n = nums.length;
    for (i=0;i<n;i  ){
        if (nums[i]==target) {
            return (i);
        }
    }
    
    return (-1);
}
  • Related