You could solve it like this:
private static final int MIN = -180;
private static final int MAX = 180;
public static void main(String[] args) {
System.out.println(keepInRange(-150 + 90));
System.out.println(keepInRange(0 + 90));
System.out.println(keepInRange(150 + 90));
System.out.println(keepInRange(-150 - 90));
}
private static int keepInRange(final int value) {
if (value < MIN) {
/*
* subtract the negative number "MIN" from "value" and
* add the negative result to "MAX" (which is like subtracting the absolute value
* of "value" from "MAX)
*/
return MAX + (value - MIN);
}
if (value > MAX) {
/*
* subtract the number "MAX" from "value" and to get exceeding number
* add it to "MIN"
*/
return MIN + (value - MAX);
}
return value;
}
The output is:
-60
90
-120
120
According to your explanation, the last to values should be -120 and 120 and not -60 and 60 like you said in your example. The exceeding amount should be added to the “other” bound, and not from 0. 150 + 90
is 240, so it exceeds the MAX bound by 60. This then should be added to the MIN bound. The result is -120.
If this is not correct, then please update your question.
solved math need a number between -180 and 180