Note that there are some explanatory texts on larger screens.

plurals
  1. POCardinal direction algorithm in Java
    primarykey
    data
    text
    <p>This weekend I spend a few minutes thrashing together an algorithm that would take in a heading (in degrees) and return a String for the cardinal direction (I'm using it in an android compass application I'm using). What I ended up with was this:</p> <pre><code>private String headingToString(Float heading) { String strHeading = "?"; Hashtable&lt;String, Float&gt; cardinal = new Hashtable&lt;String, Float&gt;(); cardinal.put("North_1", new Float(0)); cardinal.put("Northeast", new Float(45)); cardinal.put("East", new Float(90)); cardinal.put("Southeast", new Float(135)); cardinal.put("South", new Float(180)); cardinal.put("Southwest", new Float(225)); cardinal.put("West", new Float(270)); cardinal.put("Northwest", new Float(315)); cardinal.put("North_2", new Float(360)); for (String key: cardinal.keySet()) { Float value = cardinal.get(key); if (Math.abs(heading - value) &lt; 30) { strHeading = key; if (key.contains("North_")) { strHeading = "North"; } break; } } return strHeading; } </code></pre> <p>My question is, is this the best way of doing this? It must have been done many times before although I haven't done a search for examples on the web yet. Have any other people tried this and found a neater solution?</p> <p>Edit for The Reverand's Thilo's, shinjin's and Chrstoffer's responses:</p> <p><strong>The Solution</strong></p> <pre><code>public static String headingToString2(double x) { String directions[] = {"N", "NE", "E", "SE", "S", "SW", "W", "NW", "N"}; return directions[ (int)Math.round(( ((double)x % 360) / 45)) ]; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload