1

I want to check if the two arrays have the same elements, but it says missing return statement although I have returned as below. What's the problem? My method can get correct value if I write in a void function.

public static boolean get(int[] One, int[] Two, int target) {
    int [] temp = new int[One.length];
    for (int i = 0 ; i < One.length; i ++){
        temp[i] = target - One[i];
    }

    for (int m = 0; m < temp.length; m++){
        for (int n = 0; n < Two.length; n ++){
            if (temp[m]==Two[n]){
                return true;
            }  
           else return false;
        }

    }

}

1
  • your code is not true at all , i've answered it how to remove this bug , but i think your code is not true ... Commented Feb 9, 2017 at 22:45

4 Answers 4

1

The compiler won't accept it because it is possible to reach the end without ever returning anything. You can structure it like this so that no matter what the input is, it will always return true or false.

public static boolean get(int[] One, int[] Two, int target) {
    int [] temp = new int[One.length];

    for (int i = 0 ; i < One.length; i ++){
        temp[i] = target - One[i];
    }

    for (int m = 0; m < temp.length; m++){
        for (int n = 0; n < Two.length; n ++){
            if (temp[m]==Two[n]){
                return true;
            } 
            else {
                return false;
            } 
        }
    }

    return false;
}
Sign up to request clarification or add additional context in comments.

4 Comments

it is not efficient , try to return true in for loop
you are new to stackoverflow , look at the op , it returns false in the else add it to , i'm not gonna downvote your solution , correct it , i'll upvote it :)
be aware of these little things , in stackoverflow people gonna downvote such answers , so you can't get promotion in it , good luck ;)
where are you from ?
0

It's possible for the function to finish without returning if either temp.length or Two.length are 0.

Comments

0

i have no idea what you gonna do , but if you add a return false; into the last line of your method , it would work

public static boolean get(int[] One, int[] Two, int target) {
    int [] temp = new int[One.length];
    for (int i = 0 ; i < One.length; i ++)
        temp[i] = target - One[i];

    for (int m = 0; m < temp.length; m++){
        for (int n = 0; n < Two.length; n ++){
            if (temp[m]==Two[n]) return true;
            else return false;
        }
    }
    return false;
}

Comments

0

Think about what will happen if temp.length is 0 ...

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.