Return Methods
A return method is a method that returns a value. It may perform
some function previously, but it must always return a value for all
logical paths.
Examples:
Note: You must always return a value (no matter what).
In the example below, it would be best to have a
precondition that states that x2!=x1.
public double calculateSlope(int x1, int y1, int x2, int y2)
{
if (x1 != x2)
{
return(double)(y2-y1)/(x2-x1);
}
else
{
return 0;
}
}
// abs function (method)
// There is already a function in the Math library that does this,
// so this is unnecessary except to show you how to write a return method.
// In fact, the abs method in the Math library is overloaded, so you can
// call it with a double, float, int, or long parameter.
// Math.abs()
public int abs(int x)
{
if (x < 0)
{
return -1*x;
}
else
{
return x;
}
}