I'd like to run multiple methods using the same loop, but I'm running into a problem.
Let's say I have the following method:
void xy1() {
int y1 = 0;
for (int x = 0; x < 10; x++){
y1 += x;
}
}
Works fine, all I have to do is call on it in the constructor.
Now, let's say I also want to use another method, but with a different initial value of y:
void xy2() {
int y2 = 1;
for (int x = 0; x < 10; x++){
y2 += x;
}
}
Also works fine.
What I want however, is to have both methods run at the same time, in the same loop. An obvious solution would be to merge them into one method:
void xy (){
int y1 = 0;
int y2 = 1;
for (int x = 0; x < 10; x++){
y1 += x;
y2 += x;
}
}
This gets messy fast though, when more and more variables are introduced. So what I tried doing was putting the loop in the constructor, and have it call on the methods every cycle:
Constructor (){
int y1 = 0;
int y2 = 1;
for (int x = 0; x < 10; x++){
xy1(y1, x);
xy2(y2, x);
}
}
With the methods looking like this:
void xy1(int y1, int x) {
y1 += x;
}
void xy2(int y2, int x) {
y2 += x;
}
The problem with this is of course that every time the constructor calls on the methods, it simply passes down the initial values of y1 and y2, not the values that they should currently have. Defining the initial values inside the methods would just cause them to be reset in the same way each cycle.
So what I need, is for the methods to somehow remember the last value of y for the new calculation. I feel like there's an obvious solution I'm missing... I've tried using google but I don't really know what search terms to use.
And while we're at it, since the calculations performed by the methods are the same, it would be great if I could simply define a single method xy, and have the constructor use it with different initial y values (in the same loop). The problem with this would be that there would have to be separate instances of y, so prevent one y being manipulated by two instances of the method (Did that make any sense? This is a problem that I expect to run into, so I'm not entirely sure what shape it'll take. I can always create a new question.)
Thanks for any help!
y1 = xy1(y1, x); y2 = xy2(y2, x);in theConstructorso that you record the updated values of the variables.return y1 + x;? What are you actually trying to solve? Those methods don't seem to do anything useful. Why do you even want those to operate "in the same loop" instead of calling both of the original methods one after the other?