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.
Are you asking about absolute values?
Math.abs(...) is the function you probably want.
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;
Use the abs
function:
int sum=0;
for(Integer i : container)
sum+=Math.abs(i);
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.
You're looking for absolute value, mate. Math.abs(-5)
returns 5...
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));