I am building a compass, and need to return a different String for the cardinal direction depending on what 22.5 degree interval the user is currently in.
For reference, please look at this picture.
Here is a sample of my current code:
if ((azimuth >= 348.75 && azimuth <= 360) || (azimuth >= 0 && azimuth <= 11.25))
{
return "N";
}
else if (azimuth < 348.75 && azimuth >= 326.25)
{
return "NNW";
}
This series of else if
statements continues in 22.5 degree intervals until all cardinal directions are covered. Is there a more efficient way to do this? Currently, Android Studio/IntelliJ is giving an error message saying this method is too complex to analyze by data flow algorithm
. Regardless of the error message, I think there might be a more elegant way to do this, but I can't think of it at the moment.
Any ideas? Thanks!
Integer arithmetic is your friend:
private static final POINTS = new String[]{
"N", "NNE", "NE", "ENE",
"E", "ESE", "SE", "SSE",
"S", "SSW", "SW", "WSW",
"W", "WNW", "NW", "NNW"};
public static String point(int azimuth) {
return POINTS[(int)((azimuth + 11.25) % 360 / 22.5)];
}
This will work for any positive value.
If you prefer a more in-line approach:
return new String[]{"N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE",
"S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"}
[(int)((azimuth + 11.25) % 360 / 22.5)];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With