1. Member Join Date
Apr 2012
Posts
16
Rep Power
0

## A little problem about a Nine-times Table

I try to make a nine-times table program example on a book and here's the code.
Java Code:
```public class NineTable2 {
public static void main(String[] args) {
for (int i = 2, j = 1; j < 10; i = (i == 9) ? ((++j / j) + 1) : (i + 1)) {
System.out.printf("%d*%d=%2d%c", i, j, i * j, (i == 9 ? '\n' : ' '));
}
}
}```
it works ok, but If I change the code:
Java Code:
`i = (i == 9) ? ((++j / j) + 1) : (i + 1)`
to
Java Code:
`i = (i == 9) ? ((j++ / j) + 1) : (i + 1)`
When i == 9 , it always makes i = 1.
But does not j++ is as same as ++j?if ++j can make i = 2,so should j++,but it doesn't happen and i always equals 1.Can somebody explain it why Sorry for my poor English, hope you can understand my question.
Best Regard  Reply With Quote

2. ## Re: A little problem about a Nine-times Table

j++ is as same as ++j
No
The position of the ++ determines when the value of the variable is returned.
If it is before the variable the value returned is after the ++ is done, if after, the value is before the ++ is done.  Reply With Quote

3. Member Join Date
Apr 2012
Posts
16
Rep Power
0

## Re: A little problem about a Nine-times Table

So if j = 1,then (++j/j) + 1 means j will add 2 first , then return value, so (++j/j) + 1 will run as ((1+1)/2) + 1 and equals 2,right?
And ((j++)/j) +1 means ((1+1)/1)+ 1 and equals 3,right?
But when I run the program with ((j++)/j) +1, I guess it runs (0/1)+1=1,so i is always 1, I don't know why ((j++/j)+1 = 1
Last edited by blackdiz; 05-04-2012 at 04:09 AM.  Reply With Quote

4. Member Join Date
Sep 2011
Posts
59
Rep Power
0

## Re: A little problem about a Nine-times Table Originally Posted by blackdiz So if j = 1,then (++j/j) + 1 means j will add 2 first , then return value, so (++j/j) + 1 will run as ((1+1)/2) + 1 and equals 2,right?
And ((j++)/j) +1 means ((1+1)/1)+ 1 and equals 3,right?
But when I run the program with ((j++)/j) +1, I guess it runs (0/1)+1=1,so i is always 1, I don't know why ((j++/j)+1 = 1
Almost but not quite.

++j will add 1 to j before the result of j is returned.
j++ adds 1 to j after the result of j is returned
Therefore:
if j = 1
++j will return 2.
j++ will return 1 but will be 2 after.

Demonstration:

(++j/j)
if j = 1 this will translate to:
(2/2)
No matter what j is, this will always evaluate to 1

(j++/j)
if j = 1 this will translate to:
(1/2)
now this is the important part
at first glance this appears to evaluate to .5
BUT! The data type you are using is int therefore it will evaluate to 0!

Reason:
int cannot hold numbers with decimal places therefore truncates the decimals leaving the hole number(in this case 0).

Conclusion:
(++j/j) + 1
(2/2)+1
1+1
2

(j++/j) + 1
(1/2) + 1
0 + 1
1
Last edited by brynpttrsn; 05-04-2012 at 04:39 AM.  Reply With Quote

5. Member Join Date
Apr 2012
Posts
16
Rep Power
0

## Re: A little problem about a Nine-times Table  Reply With Quote