Elementary question converting negative numbers to 0 in Java

James Shelton :

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?

Elliott Frisch :

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).

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=415577&siteId=1