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

 Posting Rules You may not post new threads You may not post replies You may not post attachments You may not edit your posts BB code is On Smilies are On [IMG] code is On HTML code is OffTrackbacks are On Pingbacks are On Refbacks are Off Forum Rules

 Similar Threads Thread Thread Starter Forum Replies Last Post ryles Python 3 07-26-2009 04:13 PM Hari Sekhon Python 0 06-20-2006 08:07 AM joshc C Programming 5 03-31-2005 02:23 AM TheVooDooChild Java 2 02-24-2005 06:39 PM T. Onoma Ruby 9 12-15-2003 03:34 AM