views:

9025

answers:

8

Hi, I'm sure this is a very simple question! I have a Java method in which I'm summing a set of numbers. However, I want any negatives numbers to be treated as positives. So (1)+(2)+(1)+(-1) should equal 5. I'm sure there is very easy way of doing this - I just don't know how!! Any tips would be much appreciated.

+26  A: 

Just call Math.abs?

Jon Skeet
Jon Skeet gets another one. ;)
JB King
Note the edge cases, e.g. Math.abs(Integer.MIN_VALUE) = Integer.MIN_VALUE.
Zach Scrivena
+4  A: 

Are you asking about absolute values?

Math.abs(...) is the function you probably want.

Uri
+19  A: 

The concept you are describing is called "absolute value", and Java has a function called Math.abs to do it for you. Or you could avoid the function call and do it yourself:

number = (number < 0 ? -number : number);

or

if (number < 0)
    number = -number;
Paul Tomblin
Oh, dilemma time - there are so many equally good answers, that I might as well delete mine. But then I'd lose 40 points, and I'll never catch Jon Skeet if I do that.
Paul Tomblin
Sorry -1 for reinventing a standard library call.
cletus
@cletus, did you notice that I had already mentioned the standard library call? Or that in this case, the "reinvent" takes fewer instructions that calling the library?
Paul Tomblin
Also worth understanding the details behind the library call. Especially if there are side effects to the library call, or performance issues like Paul mentions.
simon
+9  A: 

Use the abs function:

int sum=0;
for(Integer i : container)
  sum+=Math.abs(i);
jpalecek
+5  A: 

The easiest, if verbose way to do this is to wrap each number in a Math.abs() call, so you would add:

Math.abs(1) + Math.abs(2) + Math.abs(1) + Math.abs(-1)

with logic changes to reflect how your code is structured. Verbose, perhaps, but it does what you want.

Eddie
You could make it less verbose with a static import.
Dan Dyer
+5  A: 

You're looking for absolute value, mate. Math.abs(-5) returns 5...

Hexagon Theory
+3  A: 

You want to wrap each number into Math.abs(). e.g.

System.out.println(Math.abs(-1));

prints out "1".

If you want to avoid writing the Math.-part, you can include the Math util statically. Just write

import static java.lang.Math.abs;

along with your imports, and you can refer to the abs()-function just by writing

System.out.println(abs(-1));
Henrik Paul
+6  A: 

1 more

Why don't you use:

Ma..ab....

... Oh.

OscarRyz