Question: 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;}

```

Answer: 
You can use following function:

```
public static int getHeading(int val)
{
    val %= 360;
    return (val < 0)? (val+360) :val;
}

```

See it working [here in C++](https://ideone.com/MKUxws) and [here in Java](https://ideone.com/8uJBkE):

```
class Test
{
    public static int getHeading(int val)
    {
        val %= 360;
        return (val < 0)? (val+360) :val;
    }

    public static void main (String[] args) throws java.lang.Exception
    {
        int[] vals = {-360, 360, -361, 361, -1, 1};

        for(int i = 0; i< vals.length; i++)
        {
            System.out.println(vals[i] +  " = " + getHeading(vals[i]));
        }
    }
}

```

**OUTPUT:**

```
-360 = 0
360 = 0
-361 = 359
361 = 1
-1 = 359
1 = 1

```
```
     import java.util.Scanner;
public class myClass {
    public static void main (String args[]) {
Scanner sc = new Scanner(System.in); 
System.out.println("Enter a number: ");
int n = sc.nextInt();
while(n < 0){n+=360;}
while(n >= 360){n-=360;}
System.out.println(" number: " + n);

    }
}

```