for (int k = 0; k <= t - 2; k++) { double a, b; a = A.get(0) + (-gt(k + 1) + 640 + rt(0)); b = A.get(k + 1) + rt(k + 1); if (a > b) { B.add(b); } else { B.add(a); } } 

It is necessary that at each iteration of the cycle in formulas a and b first element A.get(0) from A.get(0) and A.get(k + 1) to B.get(0) and B.get(k + 1) .

  • The essence of the question is incomprehensible. If instead of A.get you need to use B.get , replace the letter A with B and use. What is the question / problem? - Regent

2 answers 2

If A and B inherit a common interface, you can declare a variable of this general type and assign A and B to it in turn.

 Base c = null; for (int k=0; k<=t-2; k++) { c = (k % 2 == 0) ? A : B; a=c.get(0)+(-gt(k+1)+640+rt(0)); b=c.get(k+1)+rt(k+1); ... } 
  • Why declare c out of cycle? - Regent
  • Yes, no difference. It's just my habit to declare a reusable variable once. - Sergey Gornostaev
 private boolean aFunc = true; private boolean bFunc = true; private double getFA(){ double result; if (aFunc) result = A.get(0); else result = B.get(0) aFunc = !aFunc; return result; } 

Next, by analogy, write the getFB () method. Well, your code will change to

  a = getFA() + (-gt(k+1)+640+rt(0)); b = getFB() + rt(k+1); 
  • Corrected, did not fully rename the variable)) bFunc will be used in getFB () analogously aFunc in getFB () - Alexander Martyntsev
  • I wrote - bFunc will be used in getFB (). result = bFunc? A.get (k + 1): B.get (k + 1); bFunc =! bFunc; - Alexander Martyntsev