How to convert a degree to a compass direction in Java

1 Answer

0 votes
// 0° → North
// 45° → North-East
// 90° → East
// 135° → South-East
// 180° → South
// 225° → South-West
// 270° → West
// 315° → North-West

public class CompassDirection {

    public static String degreesToDirection(double degrees) {
        // Normalize degrees to (0, 360)
        degrees = (degrees % 360 + 360) % 360;

        // Define compass directions
        String[] directions = {
            "North", "North-East", "East", "South-East",
            "South", "South-West", "West", "North-West"
        };

        // Each direction covers 45 degrees
        int index = (int) Math.round(degrees / 45) % 8;

        return directions[index];
    }

    public static void main(String[] args) {
        double degrees = 120;

        System.out.println("For " + degrees + " degrees, Compass direction: " 
                           + degreesToDirection(degrees));
    }
}



/*
run:

For 120.0 degrees, Compass direction: South-East

*/

 

 



answered Nov 24, 2025 by avibootz
edited Nov 24, 2025 by avibootz
...