Search code examples
javacomputer-science

How to make a number stay between 0-359? Say if it goes over by 1 to 360 it restarts to 0


So I want the number to stay always stay between 0 and 359 even if it goes over to 360, 361, 362, 363... etc or under to -1, -2, -3, -4.. etc whenever I call any of the methods below. Say if it goes over to 360 I want it to change back to 0 etc and if it goes under to -1 I want it to change to 359 etc. I have this code and it works, but the problem is that if I change the decrease or increase of amount of the heading to more than 5 then I just have to keep making for else if statements. What is a better way to write the code in which it would take into account a higher increment or decrement of the heading?

heading = 3;
public void changeHeadingLeft() {
    heading -= 5;
    if (heading == -1) {heading = 359;}
    else if (heading == -2) {heading = 358;}
    else if (heading == -3) {heading = 357;}
    else if (heading == -4) {heading = 356;}
    else if (heading == -5) {heading = 355;}
heading = 358
public void changeHeadingRight() {
    heading += 5;
    if (heading == 360) {heading = 0;}
    else if (heading == 361) {heading = 1;}
    else if (heading == 362) {heading = 2;}
    else if (heading == 363) {heading = 3;}
    else if (heading == 364) {heading = 4;}

Solution

  • You can do it without using if and loops.

    For increment, use:

    (header + amt) % 360
    

    For decrement, use:

    (360 + header - (amt % 360)) % 360    //(amt % 360) incase amt > 360
    

    Example:

    Increase 5 to header:

    (0 + 5) % 360 = 5
    

    Increase 5 to header with overflow:

    (360 + 5) % 360 = 5
    

    Decrease 5 to header:

    (360 + 100 - (5 % 360)) % 360 = 95
    

    Decrease 5 to header with underflow:

    (360 + 0 - (5 % 360)) % 360 = 355
    

    Decrease 725 to header with underflow and with amt > 360:

    (360 + 0 - (725 % 360)) % 360 = 355
    

    You could add those as methods, then you don't have to remember when to use which. For exmaple:

    class CircularNumber{
    
        private static final int BOUND = 360;
        private int header;
    
        public void add(int amt){
            header = (header + amt) % BOUND;
        }
    
        public void deduct(int amt){
            header = (360 + header - (amt % BOUND)) % BOUND;
        }
    }
    

    By applying modulus on the amount to deduct with 360 before deduction, there is no need to use a loop to keep on adding 360 to the header till it becomes positive.