for(i = 0; i<=timePassed; i ) {
y = r * x * (1 - x)
System.out.println(y)
So how do I reset the value of y every time the for loop loops so that i can assign a new value to it? I cannot wrap my head around it I have already tried to set y to 0 at the end of the loop right after printing y but that didnt seem to work. I also tried setting it to null but that gave me an error(?) I cannot understand why this is happening can someone please explain how to do this and what I did wrong?
CodePudding user response:
Are you able to update your code block to include ALL code from your class.java file? It would help us see what could be wrong, because from this code snippet, y is not saved outside of the loop, therefore for every iteration (cycle) of the loop it would be reset and re-assigned.
As someone else has said, the y value does not change at any time in the loop, as all variables used (other than y) are declared outside of the loop. This loop simply prints the same y value "timePassed" amount of times.
CodePudding user response:
Here's the code that you posted, including line numbers:
1. for(i = 0; i<=timePassed; i ) {
2. y = r * x * (1 - x)
3. System.out.println(y)
4.
Here are various comments fixes:
- Line 1: assume
i
is declared somewhere, like this:int i
- Line 1: assume
timePassed
is declared somewhere and has a value set, like:int timePassed = 5;
- Line 2: assume
y
is declared somewhere, like:int y;
- Line 2: assume
r
andx
are both declared somewhere, and have values set, like:int r = 1, x = 2;
- Lines 2-3: need semicolons to terminate each line inside the loop: add
;
at the end of each line - Line 4: add closing brace
}
to the "for" loop
Here is the code with those edits applied:
int timePassed = 5, y, r = 1, x = 2;
for (int i = 0; i <= timePassed; i ) {
y = r * x * (1 - x);
System.out.println(y);
}
Running that code produces this output:
-2
-2
-2
-2
-2
-2
The output doesn't change. Why? Because the calculation to determine each new value of "y" is the same each time: r * x * (1 - x)
. Despite being inside a loop, and with i
changing each iteration through the loop, i
is not used in the calculation at all.
Here's an edit to the code, removing the entire "for" loop (and i
), and it produces the same -2
value:
int y, r = 1, x = 2;
y = r * x * (1 - x);
System.out.println(y);
-2
To demonstrate that y
is being set each time through the loop, here's a variation of the code (including output) where i
is included in the calculation for y
.
int timePassed = 5, y, r = 1, x = 2;
for (int i = 0; i <= timePassed; i ) {
y = r * x * (1 - x) * i;
System.out.println(y);
}
0
-2
-4
-6
-8
-10