# Thread: Math.abs possibly returning a negative number

1. Member
Join Date
Oct 2013
Posts
11
Rep Power
0

## Math.abs possibly returning a negative number

Hi,

the following code gives me an error saying that "n must be positive" but the abs function should only return positive numbers so why do I get this error?

Java Code:
```y1 = 42 - Math.abs(6*(i-7));
y2 = 21 - Math.abs(3*(i-7));

int range = Math.abs(y1 - y2);

dirt = land.nextInt(range) + y2;```

2. Senior Member
Join Date
Jan 2013
Location
Northern Virginia, United States
Posts
5,502
Rep Power
9

## Re: Math.abs possibly returning a negative number

Not enough information provided. You need to provide an Short, Self Contained, Correct Example and the error message. Otherwise, we are just guessing.

Regards,
Jim

3. Member
Join Date
Oct 2013
Posts
11
Rep Power
0

## Re: Math.abs possibly returning a negative number

Hi,

The code I posted is the only code that pertains to the problem. It is part of a larger method that is used in the main method. here is the error it gives me:

Exception in thread "main" java.lang.IllegalArgumentException: n must be positive
at java.util.Random.nextInt(Random.java:250)
at mapGenerator.island(mapGenerator.java:39)
at mapGenerator.main(mapGenerator.java:15)

I know what the error is saying (the random function can not take a negative value as an argument). the problem I have is that according to my code the argument should never be negative. so why does it tell me that it is getting a negative argument? when I assign the variable range as the value of Math.abs(-6) it runs just fine. but when it is Math.abs(y1 - y2) it gives me the error.

4. Senior Member
Join Date
Jan 2013
Location
Northern Virginia, United States
Posts
5,502
Rep Power
9

## Re: Math.abs possibly returning a negative number

No you still need to provide more code. What is the value of i? We certainly don't know. Perhaps range is zero. Did you print it out?

Regards,
Jim

5. Member
Join Date
Oct 2013
Posts
11
Rep Power
0

## Re: Math.abs possibly returning a negative number

Ok Im sorry for that, I now understand what you mean by more information. Luckily the problem was that the value was zero at one point, I was thinking that zero was a positive number. Thank you for your help.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•