Velvet Star Monitor

Standout celebrity highlights with iconic style.

news

How to obtain return type double?

Writer Mia Lopez

I have created a method which is supposed to return type double and here is my code

private void myMethod()
{ if(myArrayList.size() >= 2) { Double t = myArrayList.get(myArrayList.size()-1); Double d = myArrayList.get(myArrayList.size()-2); Double result = ( t+ d ) / 2 ; System.out.println("Average is: "+result); }
}

I change void to double and just after system.out..... line i added return result but this gives an error!! Could you please tell me how exactly i can change this method so that i obtain a return type of double?

3

5 Answers

every branch has to give a double as return if you change the type of the method to double. Thus your error is because only if the "if" will be entered there will be an double as return, but not if not!

private Double myMethod()
{ Double result = 0; // has to be initialised ... if(myArrayList.size() >= 2) { Double t = myArrayList.get(myArrayList.size()-1); Double d = myArrayList.get(myArrayList.size()-2); result = ( t+ d ) / 2 ; System.out.println("Average is: "+result); } return result;
}

this should work

I think your rerun was inside the if condition. So method is worried about what happens when if condition is not true. You need to handle that as well.

private double myMethod()
{ double result=0; if(myArrayList.size() >= 2) { Double t = myArrayList.get(myArrayList.size()-1); Double d = myArrayList.get(myArrayList.size()-2); result = ( t+ d ) / 2 ; System.out.println("Average is: "+result); } return result;
}
1

To sum things up, all the previous answer are right, but lack some minor detail, like @dinesh707 says, you must be able to return on every method branch (unless an exception occurs). And also be sure to declare the result variable outside the decision/if block, and to declare that the method return a double, and you should go with the double primitive, not the boxed version.

so the code looks like:

private double myMethod() {
double result=0;
if(myArrayList.size() >= 2) { double t = myArrayList.get(myArrayList.size()-1); double d = myArrayList.get(myArrayList.size()-2); result = ( t+ d ) / 2 ; System.out.println("Average is: "+result);
}
return result; 

}

2

You are missing return type of the method. A method must return a value of method type. if method is declared void then it means that method do not return any value.

private double myMethod()
{
double result =0;
if(myArrayList.size() >= 2)
{ double t = myArrayList.get(myArrayList.size()-1); double d = myArrayList.get(myArrayList.size()-2); result = ( t+ d ) / 2 ; System.out.println("Average is: "+result);
}
return result;
}
2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy