balabalabalalala
balabalabalalala

Reputation: 7

Boolean class missing a return statement java

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

    }

}

Upvotes: 1

Views: 259

Answers (4)

Pali
Pali

Reputation: 1347

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

Upvotes: 0

jarthur
jarthur

Reputation: 422

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

Upvotes: 1

Mohsen_Fatemi
Mohsen_Fatemi

Reputation: 3391

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

Upvotes: 0

Matt Wisniewski
Matt Wisniewski

Reputation: 91

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

Upvotes: 0

Related Questions