Velocity Reviews > Java > Java Arithmetic - Using MOD (%)

# Java Arithmetic - Using MOD (%)

Steven Davies
Guest
Posts: n/a

 02-01-2005
I'm trying to iterate over an array, copying objects from one array into
another and "wrap around" over the boundary of the initial array, but I
have a problem:

I'm using the % operator to try and get the value to wrap around, but it
keeps jumping to negative numbers.

Here's a code snippet:

> for (int x = 0; x < (sightDist * 2 + 1); x++) {
> for (int y = 0; y < (sightDist * 2 + 1); y++) {
> visibleArray[x][y] = theTiles[oldX][oldY];
> oldY = (oldY + 1) % 100;
> }
> oldY = (oldY - (sightDist * 2 + 1)) % 100;
> oldX = (oldX + 1) % 100;
> }

Does anyone have any idea why the statements at the bottom don't seem to
mod the number properly? Any more details you need, ask me

(oldX and oldY are definitely positive before this is executed, the
array called theTiles is 100 by 100.)

Thanks,
Steven Davies

klynn47@comcast.net
Guest
Posts: n/a

 02-01-2005
What value does it give you?

Yamin
Guest
Posts: n/a

 02-01-2005
a negative return from a mod is perfectly valid mathemetically.
99 % 100 is the same as -1 % 100. I haven't done any research into
Java's implementation of mod, but perhaps it is returning that negative
version. Assuming this is the case...you can get the mod you want by:
value = equation % 100;
if( value < 0) value= value + 100;

Yamin

Steven Davies
Guest
Posts: n/a

 02-01-2005
Yamin wrote:
> a negative return from a mod is perfectly valid mathemetically.
> 99 % 100 is the same as -1 % 100. I haven't done any research into
> Java's implementation of mod, but perhaps it is returning that negative
> version. Assuming this is the case...you can get the mod you want by:
> value = equation % 100;
> if( value < 0) value= value + 100;
>
> Yamin

Yeah, I read the Java language spec and indeed if you do z = x % y and x
is negative, so is your result. A quick z+=array.length worked a treat

Thanks.
--
Steven Davies, sed3
Computer Science and German