I'm struggling to fully understand copy-in / copy-out passing in Java. I'm not asking if Java is pass-by-value or pass-by-reference, I'm just having trouble understanding it in this scenario.
I need to update the floats (f1, f2, and f3) in the main method, adjusting the distance using the adjustDistance() method. This is for a homework quiz, so what I can/can't change is limited. Looking for a bit of info as to what I need to do and why.
This is the code:
public class Flow {
public static String formatF1F2F3(float f1, float f2, float f3)
{
return
"f1 = " + f1 + ", f2 = " + f2 + ", f3 = " + f3;
}
// The new record type is needed to
// so that the two results
// of adjustDistance can be returned together.
//
// adjustDistance is a method inside this
// class so that parameter passing is simpler
private static class TwoFlows
{
public float flow1;
public float flow2;
public TwoFlows(float flow1, float flow2)
{
this.flow1 = flow1;
this.flow2 = flow2;
}
public void adjustDistance()
{
if ( Math.abs(flow1 - flow2) < 10 )
{
if(flow1 > flow2)
{
flow2 = flow2 / 3;
flow1 = flow1 + flow2;
flow1 = flow1 + flow2;
}
else
{
flow1 = flow1 / 3;
flow2 = flow2 + flow1;
flow2 = flow2 + flow1;
}
}
}
}
public static void main(String[] args)
{
float f1, f2, f3;
f1 = 3; f2 = 3; f3 = 4;
System.out.println(formatF1F2F3(f1,f2,f3));
// TASK:
// Write code that it simulates *copy-in copy-out* passing
// of formal parameters flow1 and flow2 to method adjustDistance.
// only alter code below this comment
// my attempt:
TwoFlows twoFa = new TwoFlows(f2, f3);
twoFa.adjustDistance();
System.out.println(formatF1F2F3(f1,f2,f3));
TwoFlows twoFb = new TwoFlows(f1,f2);
twoFb.adjustDistance();
System.out.println(formatF1F2F3(f1,f2,f3));
TwoFlows twoFc = new TwoFlows(f3,f3);
twoFc.adjustDistance();
System.out.println(formatF1F2F3(f1,f2,f3));
} }
OUTPUT:
f1 = 3.0, f2 = 3.0, f3 = 4.0
f1 = 3.0, f2 = 3.0, f3 = 4.0
f1 = 3.0, f2 = 3.0, f3 = 4.0
f1 = 3.0, f2 = 3.0, f3 = 4.0
If I don't initialise new TwoFlows() each time, I get an error. I don't think the flow1 and flow2 update as I'm expecting them to.
The expected output I believe is:
f1 = 3.00, f2 = 3.00, f3 = 4.00
f1 = 3.00, f2 = 1.00, f3 = 6.00
f1 = 3.67, f2 = 0.33, f3 = 6.00
f1 = 3.67, f2 = 0.33, f3 = 10.00