When using only if, I had to return some integer
public class solution {
public static int binarySearch(int arr[], int x,int si,int ei){
if(si>ei){
return -1;
}
int mid=(si+ei)/2;
if(arr[mid]==x){
return mid;
}
if(arr[mid]>x){
return binarySearch(arr,x,si,mid-1);
}
if(arr[mid]<x){
return binarySearch(arr,x,mid+1,ei);
}
return 0;
}
}
but when using if-else-if, I don't have to return any integer, why?
public class solution {
public static int binarySearch(int arr[], int x,int si,int ei){
if(si>ei){
return -1;
}
int mid=(si+ei)/2;
if(arr[mid]==x){
return mid;
}
else if(arr[mid]>x){
return binarySearch(arr,x,si,mid-1);
}
else {
return binarySearch(arr,x,mid+1,ei);
}
}
}
The compiler can not guess that the last if condition will always be true. So you have to provide a return value in case it is false. Even though it will never happen. You could even get rid of the last if statement.
public class solution {
public static int binarySearch(int arr[], int x,int si,int ei){
if(si>ei){
return -1;
}
int mid=(si+ei)/2;
if(arr[mid]==x){
return mid;
}
if(arr[mid]>x){
return binarySearch(arr,x,si,mid-1);
}
return binarySearch(arr,x,mid+1,ei);
}
}
When a method has return type in signature, something should be returned from the method in all condition. And that check is made at compile time in Java.
When you use if in your code logically that condition can be true or false. If that's true the method will get something returned from if block. But if the condition is false, method won't get anything to return back (because code inside if condition in not executed). So in that case method need something to return as default when if condition is resulted as false. From first method if all if conditions like
if(si>ei){
return -1;
}
int mid=(si+ei)/2;
if(arr[mid]==x){
return mid;
}
if(arr[mid]>x){
return binarySearch(arr,x,si,mid-1);
}
if(arr[mid]<x){
return binarySearch(arr,x,mid+1,ei);
}
are false. Method won't be in situation to return anything.
On the other place when you use else with if (weather it is if-else or if-elseIf-else) then condition when if is false (or elseIf is false), the else part will return something from method. So always there will be something to return from method. In second method like
if(arr[mid]==x){
return mid;
}
else if(arr[mid]>x){
return binarySearch(arr,x,si,mid-1);
}
else
return binarySearch(arr,x,mid+1,ei);
}
if the first if condition is true mid will be returned. If arr[mid]>x is true binarySearch(arr,x,si,mid-1); result will be returned. If both are true else will always be there to return something (in your case binarySearch(arr,x,mid+1,ei);).
Because all possible outcomes of your second method's work will return something. You always need to ensure that when your method is not void.
In first case you need to specify return value for the case, when none of your three if statements' conditions is true.
if(arr[mid]==x){
return mid;
}
if(arr[mid]>x){
return binarySearch(arr,x,si,mid-1);
}
if(arr[mid]<x){
return binarySearch(arr,x,mid+1,ei);
}
However, it is clear to see that you will never face a situation, when all the above conditions are false, but compiler cannot figure this out, so you need to design your code that way, in which compiler will know that in all possible conditions your method will return value. So the second implementation is more "clean" and logically correct
you have set the return type to int. When you are using if statements, there is no surety that one of the if statements has to work and you will get the return value.
if()
{
return value;
}
if()
{
return value;
}
In the above code both ifs can work or both can not work if conditions are not satisfied. therefore it might be possible that we will not get a return value.
and in else if, else case we have surety that one of the case will definitely work and we will get a return value 100%
if()
{
return value;
}
else if()
{
return value;
}
else{
return value;
}
in the above code only one of the if condition will work and we will always get a return value.
Related
I'm learning Java at the moment and have a task where I should create a method that keeps asking the user for input until one of two keywords are entered. It should then, depending on that return an int.
public static int getCommand(){
String command = IOTools.readString("Enter Command!");
if (command.equals("exit")){
return 1;
} else if (command.equals("shift")){
return 0;
} else {
getCommand();
}
}
The problem I'm having is that eclipse tells me to either change the return type to void or add a return statement after the if block.
Is there something wrong with my recursive approach?
You are missing the return statement on your recursive call
public static int getCommand(){
String command = IOTools.readString("Enter Command!");
if (command.equals("exit")){
return 1;
} else if (command.equals("shift")){
return 0;
} else {
return getCommand(); // Added return here
}
}
you need to add a return type in last case
public static int getCommand(){
String command = IOTools.readString("Enter Command!");
if (command.equals("exit")){
return 1;
} else if (command.equals("shift")){
return 0;
} else {
return getCommand();
}
}
this function getCommand(); call is returning an int value but not in else case so if the control falls inside your else case then your recursive functions calls will be executed though there is no assurance that getCommand(); will return an int value due to else case so compiler detects that hence the error and according to this case where return type is not void , java says
Every execution path in a function must lead to a RETURN statement
Return statement is missing here
else {
getCommand();
}
All paths of your methode need to return something.
This is my method to find if a particular node is there in a binary tree.Here's my method and it works fine.
public boolean find(BinaryNode p,int x){
if(p==null){
return false ;
}
else{
if(x==p.element){
return true;
}
else if(x<p.element){
return find(p.left,x);
}
else {
return find(p.right,x);
}
}
}
My question is if I don't insert return keyword inside else if(x<p.element){ and else { I get an error as missing return statement.
Say I have a binary tree consisting of elements 5,4,6,60,25,10 .
So if i am searching for 10 there's a time that
if(x==p.element){
return true;
is satisfied because of recursive calls.Then there's a return statement to be found.
If i am searching for an element that's not in tree eventually I would reach the statement
if(p==null){
return false ;
},there we find a return statement.
Therefore even I don't have the return in else if and else clauses somehow there's a way that I finally reach a return statement right?So what's wrong with not having return keyword in else if and else clauses.
Why do I have to have it there?
Why can't I do it as
`public boolean find(BinaryNode p,int x){
if(p==null){
return false ;
}
else{
if(x==p.element){
return true;
}
else if(x<p.element){
find(p.left,x);
}
else {
find(p.right,x);
}
}
}`
The closest to the way you want your if-else if-else clause to behave is using the ? conditional expression:
public boolean find(BinaryNode p,int x)
{
if(p==null) {
return false ;
}
else {
return (x==p.element)?true:(x<p.element?find(p.left,x):find(p.right,x));
}
}
Other option is to store the value to be returned in a local variable and only return it at the end of your method:
public boolean find(BinaryNode p,int x)
{
boolean returnValue = false;
if(p!=null)
{
if(x==p.element){
returnValue = true;
}
else if(x<p.element){
returnValue = find(p.left,x);
}
else {
returnValue = find(p.right,x);
}
}
return returnValue;
}
And my favorite way, using short-circuit evaluation of logical expressions:
public boolean find(BinaryNode p,int x)
{
if(p==null) return false;
return x==p.element || (x<p.element && find(p.left,x)) || find(p.right,x);
}
Since Java's || and && operators won't evaluate their right part expression when the left part already determines their result. If x==p.element is true, then true will be returned without evaluation the rest of the line. If not, then (x<p.element && find(p.left,x)) will be evaluated following the same rule.
Note how find(p.left,x) won't be evaluated when x<p.element is false.
You need return statement because the find-function in the else if - else statement will return to the caller after its done, but the first-call function still have to return a value to the caller
Therefore even I don't have the return in else if and else clauses somehow there's a way that I finally reach a return statement right?
No compiler doesn't know about it. Compiler doesn't know what will be value of x and p at run-time.
Compiler simply checks for all the possibilities of the return statement and there must be exit point of the method.
You need to provide the logic to move either in right direction or left direction of the binary tree.
The last two else-if are not responsible to actually return the result of the find method its used just to move in the right direction of the tree. Ultimately final result of the the find method will come out by first two if-else clause.
When it comes to recursion, here is where I struggle, I know the edge case for when the function should be true, but because I have to add a return false statement as well, and somewhere deep in the call stack, it does become true(which is the whole point of examining!), I want the final outcome to be true, and for the recursion to stop. But eventually, it finds its way to the return false, simply because its the last thing the function does.
public boolean isPathHelper(Node node, String input){
if(node.accept == true){
return true;
}else{
if(input.length() == 0){
return false;
}
isPathHelper(getNextState(node, input.charAt(0) -'0'), input.substring(1));
return false;
}
How do I deal with this scenario? I know global variables can help, but I was hoping there's a gap in my knowledge instead.
Try this:
public boolean isPathHelper(Node node, String input, int count){
if(input.length() == 0){
return false; //I can't go any further: return "failed"
}
else if(count == input.length()){
return true; //if I ever reach here, then I am done: return "success"
}
// else call self recursively
return isPathHelper(
getNextState(node, input.charAt(0) -'0'), input.substring(1), count+1);
}
Just examine your logic and your data carefully enough to be SURE you hit "count == input.length()" at some point. Preferably at some point before you run out of stack ;)
Eclipse keeps telling me to add a return statement to the method, even though I did so.
public class PrefixCode {
public String isOne(String[] words) {
if(words.length==1) {
return "Yes";
}
ArrayList<Integer> indexPositions= new ArrayList<Integer>();
for(int i=0;i<words.length;i++) {
String firstWord=words[i];
java.util.List<String> listOfWordsToCheck = new ArrayList<String>(Arrays.asList(words));
listOfWordsToCheck.set(i,null);
for(int j=0;j<listOfWordsToCheck.size();j++) {
String secondWord= listOfWordsToCheck.get(j);
if(firstWord.startsWith(secondWord)==true) {
indexPositions.add(j);
}
else if(firstWord.startsWith(secondWord)==false);
}
}
if(indexPositions.size()==0) {
return "Yes";
}
else if(indexPositions.size()!=0) {
Collections.sort(indexPositions);
return "No,"+indexPositions.get(0)+"";
}
}
}
My return statements are outside of the for loops, so I don't understand what's wrong here.
There is no default return. The only returns you are making are if some conditions are true. What if the conditions are false?
Add a return after the last else block and you are all good to go.
The else block is redundant. What lies inside the else block should be be without else.
Since you have added if, else if, you need to else to that control flow to satisfy the compiler. Logically, size can be either zero or more than zero. So, you need to have if and else part only
if(indexPositions.size()==0){
return "Yes";
} else if(indexPositions.size()!=0){
Collections.sort(indexPositions);
return "No,"+indexPositions.get(0)+"";
} else {
// return what?
}
You can simplify this logic by,
if(indexPositions.size() == 0) {
return "Yes";
} else { //size more than zero
Collections.sort(indexPositions);
return "No,"+indexPositions.get(0) + "";
}
you should use else instead of
else if(indexPositions.size() != 0) {
Collections.sort(indexPositions);
return "No,"+indexPositions.get(0) + "";
}
The compiler doesn't know if the if conditions are going to succeed. So, you need to add a default return out of those if (even if your if conditions cover all possible cases!)
One of the best practice is to have only one return at the method end! Like this:
public String isOne(String[] words) {
String isOne = null;
if(words.length==1){
isOne = "Yes";
}
...
if(indexPositions.size()==0){
isOne = "Yes";
}
else if(indexPositions.size()!=0){
Collections.sort(indexPositions);
isOne = "No,"+indexPositions.get(0)+"";
}
return isOne;
}
Sometimes you may initialize the variable with a default value too, even if in this case is not needed :
String isOne = "No";
In also in your code there is an "error", the indexPositions.size may only be 0 or more, so you may want to use else instead of else if, and complete the graph. In this case eclipse won't tell you to add a return statement anymore, even if you use the return inside the condition block.
if(indexPositions.size()==0) {
return "Yes";
}
else {
Collections.sort(indexPositions);
return "No,"+indexPositions.get(0)+"";
}
I usually do this by declaring a boolean at the start of the function and set it to false. If for whatever reason the function says that variable is gonna be true. I set the declared variable to true instead of returning true. At the end of the function i return that declared variable.
It then has its default return and if the variable was set to true, it returns true.
I'm trying to make a boolean method, but it's not recognizing I have a return statement. What should I do?
public boolean isThreeKind( int rankHist[]) {
for (int i=0;i<=13;i++){
if (rankHist[i]>=3){
return true;
}else{
return false;
}
}
}
Your code does not make sense. There is no point in having a loop if you're always going to run the code inside the loop exactly once. I think you must have misunderstood. What are you trying to do?
Assuming the method only has to return true or false if it is greater than equal to 3,
would recommend to keep it simple.
Also, Please Note:
Loop through the i=0 to i< rankHist.length incase the array contains less than 13 elements you will encounter an ArrayOutOfBoundException.
If it contains more than 13 elements, the output might be incorrect.
.
public boolean isThreeKind( int rankHist[]) {
for (int i=0;i<rankHist.length;i++){
if (rankHist[i]>=3){
return true;
}
}
return false;
}
I think what he wants is if every element in the 13 are >=3, he should return a true, else ways he should return a false.
public boolean isThreeKind( int rankHist[])
{
for (int i=0;i<=13;i++)
{
if (rankHist[i]<3)
{
return false; // Will return false if either of the element have value <3
}
}
return true; // Will return true only if all the 13 elements have value >=3
}
This is literally what your code is doing right now:
public boolean isThreeKind( int rankHist[]) {
return rankHist[0] >= 3;
}
That is it, and I am assuming this is not what you are attempting to do. So if you tell us what you are actually trying to accomplish we can help you more.
In java, You always gotta keep track of returning something EVERYWHERE the method can exit. If it can exit without hitting a return statement, you'll see that error.
So, for your code, to modify it and make it see it, you would need to have it say:
public boolean isThreeKind( int rankHist[]) {
for (int i=0;i<=13;i++){
if (rankHist[i]>=3){
return true;
}else{
return false;
}
}
return false;
}
Or true, if you would rather that.
You should avoid multiple return statement.
You can use a flag. Declare the flag outside the for loop, then assign the value accordingly, and do not miss the break statement.
Do it like that:
public boolean isThreeKind( int rankHist[]) {
boolean value = false;
for (int i=0;i<=13;i++){
if (rankHist[i]>=3){
value = true;
break;
}
}
return value;
}