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?
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:
}