Java: Error-"This method must return a result of type Boolean"
A function with a return type (in this your function "inarray()") must always be able to return a value (of type boolean, in this case).
Dissecting your function, if there is data in the array, the for-loop will run and will spit out a return true or return false.
What if there is no data in the array though? That would mean the function doesn't ever reach the 'return true;' or 'return false;' parts of the code.
That is what the code is complaining about.
You would fix that by simply doing this:
public static Boolean inarray(String array[], String needle){ for(int i = 0; i < array.length; i++){ if(array[i]==needle){ return true; } } return false; }
I have applied a few changes to your code.
'Boolean p' is set to false. By default, you want to assume the needle-word is not contained in the array, unless proven otherwise. You first set it to false, then loop through the array and if the code finds out the needle-word is there, then it decides to set the boolean to true.
I removed the else.
By saying "return false", you end a function. What your current function did, is it looks at the first word in the array and it either sees it's the needle-word or not and returns a true or false value (in your example false, as it compares 'hello' to 'are') and that's it. I assumed you wanted the function to look at the entire array?
With the above changes, it now looks at every word in the array and if one (or multiple) word(s) match the needle-word, it returns true. If it doesn't find the needle-word (doesn't enter the if statement) it will simply loop through the entire array, reach 'return p;' (which would be false, like declared above) and that's it.
Now with the above there will always be a return path.
Either it finds the needle-word in the array and returns true, or it doesn't and it returns false.
TL;DR: the reason you got an error is because not all code-paths had a return statement attached (in this case the "no content in the array" path).
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now