Java Reference
In-Depth Information
while
(n
>
0)
{
result
โ
=n ;
// similar to result=result*n;
;
}
return
result ; /
}
n
โโ
}
class
ExampleFactorial
{
public static void
main( String [ ] args )
System . out . println (
"6!="
+Toolbox . factorial (6) ) ;
}
}
Compiling and executing this program yields
6!=720
.
3.2.4 Functions with conditional statements
The former
distance
function of
3.2.2 takes two
arguments
x
and
y
of type
double
and returns the absolute value of their difference in a result of type
double
. Let us recall the previous code...
static double distance(double x, double y)
{double result;
if (x>y) result=x-y;
else result=y-x;
return result;
}
ยง
This could have been rewritten more compactly as follows:
static double distance(double x, double y)
{if (x>y) return x-y;
else return y-x;}
In case functions or procedures use branching conditionals (such as
if else
or
switch case
statements), we always have to make sure that whatever the
instruction workflow, the function will always reach an appropriate
return
statement. The compiler checks all these different execution paths and may
complain with a
missing return statement
message error if this property is
not met. For example, try to replace the
distance
function by this erroneous
code:
static double distance(double x, double y)
{double result;
if (x>y) result=x-y; // forgot voluntarily the return statement
else return y-x;}
Search WWH ::
Custom Search