This site requires JavaScript, please enable it in your browser!
Greenfoot back
Rich11
Rich11 wrote ...

2021/1/18

I am not sure what this code does

Rich11 Rich11

2021/1/18

#
I have this code that I watched from a youtube video that is frequently used in my game. I am not sure what it does though, can someone explain? int count = 0; count++;
danpost danpost

2021/1/18

#
Rich11 wrote...
I have this code that I watched from a youtube video that is frequently used in my game. I am not sure what it does though, can someone explain? int count = 0; count++;
int count = 0;
This declares a new variable of the primitive type int and is given the name count. It is also assigned an initial value of zero. The name is vague, as it does not indicate what exactly is being counted and therefore is probably a local field. That is, the line, as written, will be found inside of a method.
count++;
This line is equivalent to the each of the following lines:
count = count + 1;
//
count += 1;
It simply adds one to the current value of count. More precisely, it assigns count the value one more than what its value at the time was. Chances are that this line is inside (or part of) a loop structure (do, while, or for) immediately following the first line, something like this (written in a Tile class in a grid world):
int count = 0;
for (Object obj : getObjectsInRange(1,Tile.class))
{
    if (obj != this && ((Tile)obj).value == 0)
    {
        count++;
    }
}
This has count counting all the nearby Tile objects (that is not itself) whose value fields are currently set to zero.
ChafikAZ ChafikAZ

2021/1/19

#
Even I could never had said it better, to sum it all up, it's incrementing it by one every time the code (presumably an if loop) is run through.
You need to login to post a reply.