Reputation: 31
I am working on a problem in a workbook about classes and part of it tells me to set negative numbers that pop up in my output to zero in order to make sense of it. Is it possible to accomplish this without using if/else statements or conditionals? I'd like to do this by only using print format, arithmetic and classes methods. No importing anything that isn't standard to java. Is this possible, am I missing something easy?
Upvotes: 2
Views: 576
Reputation: 3826
So I'm not sure whether you are working with integers or doubles, but the basic idea here could be adapted either way. Indeed you can use math.
(n+Math.abs(n))/2
(or possible /2.0, you may play with it depending on your context) should do the trick. Where n is positive 2n over 2 is just n again. Where n is negative, n + Math.abs(n) is 0, and 0 over 2 is still 0.
Upvotes: 0
Reputation: 740
It is possible with the ternary operator. No imports necessary.
Try this number <= 0 ? 0 : number
Of course, you will have to fine tune it to your use-case, but this is as simple as it gets.
You can read more about the ternary operator in Java here :- https://www.baeldung.com/java-ternary-operator
Edit: Eliott's solution is more elegant. I will let this answer be though. :)
Upvotes: 0
Reputation: 201437
You could use Math.max(int, int)
- with parameters of n
and 0
when the value n
is negative that will result in 0
, otherwise n
.
value = Math.max(0, value); // value is 0 if negative, otherwise value
Or, if using Java 8+, Integer.max(int, int)
for the same result
value = Integer.max(0, value);
Updating the original value
shown for example purposes (it's entirely possible to use either solution here inline).
Upvotes: 8