# Java Arithmetic - Using MOD (%)

Discussion in 'Java' started by Steven Davies, Feb 1, 2005.

1. ### Steven DaviesGuest

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

Steven Davies, Feb 1, 2005

2. ### Guest

What value does it give you?

, Feb 1, 2005

3. ### YaminGuest

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

Yamin, Feb 1, 2005
4. ### Steven DaviesGuest

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

Steven Davies, Feb 1, 2005