I’m writing this very simple program from this one PDF called Think AP Java, and I can’t seem to wrap my head around this:
When I write
public static double method_1(double x)
{
double result =( x*(Math.exp(-x) ) ) + (Math.sqrt(1-Math.exp(-x) ) );
System.out.println(result);
return result;
}
I get the output of: 1.1629395387920924
But when I write:
public static double multAdd(double a, double b, double c)
{
double result = (a*b) +c;
System.out.println(result);
return result;
}
and
public static double method_2(double x)
{
double result_1 = (multAdd(1.0, (Math.exp(-x)), 0.0)) ;
double result_2 = (Math.sqrt(1.0-Math.exp(-x)));
double final_result = result_1 + result_2;
System.out.println(final_result);
return final_result;
}
The output for method_2 is: 0.36787944117144233 AND 1.1629395387920924, printed directly over one another.
What can explain the cause of this?
Any help will be greatly appreciated, as I’m only just a beginner.
When you call method_2
, you are also implicitly calling multAdd
. As per the definition of multAdd
, you are printing the result of (a*b) + c)
. Once that method_2
is done with the call to multAdd
, the execution will proceed with the remainder of the code in your method.
Eventually, it will reach the print statement (similar to what you have in the multAdd
method). Once it hits this line, the program will print the second line. This is why you have two print statements when you call method_2
.
If you want to show just one result, what you would need to do would be to omit the print statements from your methods and work with the returned value. As you can notice, all of your methods are retuning the value that they are printing.
So, you could do something like so: System.out.println(method_1(arg1));
and System.out.println(method_2(arg1));
The above code should print only two values, which are the ones you are really after.
1