public static int Count( ArrayList<Student> studentList )
{
int j = 0;
for( Student s : studentList )
{
j = j++;
}
return j;
}
What am I doing wrong?
Printable View
public static int Count( ArrayList<Student> studentList )
{
int j = 0;
for( Student s : studentList )
{
j = j++;
}
return j;
}
What am I doing wrong?
Why do you think the value of j is changed from 0? Add some println statements to see what is happening.
What is in studentList? Is the code in the loop ever executed?
What is the value of j in the loop?
Please edit your post and wrap your code with
[code=java]
<YOUR CODE HERE>
[/code]
to get highlighting and preserve formatting.
Four common ways to increment the value of the variable j: in memory:
Code java:j = j + 1;
Code java:j += 1;
Code java:j++;
Code java:++j;
Your statement in the loop is none of these. It is:
Code java:j = j++;
This has the following effect:
Since the ++ operator has higher precedence than the '=' operator, it evaluates the expression on the right of the '=' first, then it stores the value of the expression in memory:
So, here's the drill:
- Evaluates the expression j++. The value of the expression is the previous value of the variable j in memory
- This particular expression has a side-effect: It increments the value of j in memory (after the expression has been evaluated) and, therefore, stores the incremented value in memory. At this point you have incremented the value of j
However...
- Then, applying the '=' operator, it stores the previously obtained value of the expression in memory, thus overwriting the incremented value that you just stored, with the old value.
Bottom line: It stores the old value in memory each and every time.
You can easily verify my assertion by running something like the following:
Code java:
Output::
Code :i = 0: j = 0 i = 1: j = 0 i = 2: j = 0 i = 3: j = 0 i = 4: j = 0
Cheers!
Z
Hey nice questions and I am agree with Norm that you should edit your post and wrap it with
to get highlighting and preserve formatting.Code java:<YOUR CODE HERE>