DavidVV DavidVV - 3 months ago 6
Java Question

Java: trouble with i++

I am having trouble with getting why a part of code even runs:

private int m;
private int n;

public void f() {
m = (m +2) % n;
System.out.print(m+"\n");
}

public void g() {
int i=0;
m=0;
n=8;
while (i++<n) {
System.out.print("i=" + i + " m=");
f();
}
}


If I run
g()
, I get the following printed out:

i++=1 m=2
i++=2 m=4
i++=3 m=6
i++=4 m=0
i++=5 m=2
i++=6 m=4
i++=7 m=6
i++=8 m=0


As I understand it, the last line shouldn't appear. Why does
f()
get that last time?

When
f()
gets called the first time,
i = 0
and there for
i++ = 1
. (so when I print
i
, it is already equal to
1
).

When I call
f()
the second to last time,
i = 6
, and there for
i++ = 7
. That is the last entire which is
< n
(
n = 8
).

Why does the function get again called, when
i++
is already
= 8
? this really confuses me.

Answer

Try ++i instead of i++.

This has to do with the fact that:

  • ++i means "increment i and return the resulting number to the next operator to process." (PRE-increment)
  • i++ means "return the value of i to the next operation, and increment i AFTER you do so." (POST-increment)