Box the compass: Difference between revisions
→{{header|Java}}
(Added XPL0 example.) |
|||
Line 2,746:
1 North 354.38</syntaxhighlight>
=={{header|Java}}==
<syntaxhighlight lang="java">
float heading;
for (int index = 0; index <= 32; index++) {
switch (index % 3) {
case 2 -> heading -= 5.62;
}
System.out.printf("%-2d ", index % 32);
/* we could also use 'Compass.values()[index % 32]' here */
System.out.printf("%-20s", Compass.parse(heading));
System.out.printf("%6.2f%n", heading);
}
}
public enum Compass {
S, SbW, SSW, SWbS, SW, SWbW, WSW, WbS,
}
public float[] bounds() {
float bound = (360 / 32f) / 2f;
float midpoint = midpoint();
float boundA = midpoint - bound;
float boundB = midpoint + bound;
if (boundB > 360) boundB -= 360;
return new float[] { boundA, boundB };
}
public static Compass parse(float degrees) {
float[] bounds;
float[] boundsN = N.bounds();
for (Compass value : Compass.values()) {
bounds = value.bounds();
if (degrees >= boundsN[0] || degrees < boundsN[1])
return N;
if (degrees >= bounds[0] && degrees < bounds[1])
return value;
}
return null;
}
@Override
public String toString() {
String[] strings = new String[name().length()];
int index = 0;
for (char letter : name().toCharArray()) {
switch (letter) {
case 'N' -> strings[index] = "north";
case 'E' -> strings[index] = "east";
case 'S' -> strings[index] = "south";
case 'W' -> strings[index] = "west";
case 'b' -> strings[index] = "by";
}
index++;
}
String string
= strings[0].substring(0, 1).toUpperCase() +
strings[0].substring(1);
switch (strings.length) {
case 2 -> string += strings[1];
case 3 -> {
if (strings[1].equals("by")) {
string += " %s %s".formatted(strings[1], strings[2]);
} else {
string += "-%s%s".formatted(strings[1], strings[2]);
}
}
case 4 -> {
string += String.join(" ", strings[1], strings[2], strings[3]);
}
}
return string;
}
}
}
</syntaxhighlight>
Output:
<pre>
0 North 0.00
2 North-northeast 16.88
3 Northeast by north 33.75
5 Northeast by east 50.63
6 East-northeast 67.50
8 East 84.38
9 East by south 101.25
10 East-southeast 118.12
11 Southeast by east 118.13
13 Southeast by south 151.87
14 South-southeast 151.88
17 South by west 185.63
18 South-southwest 202.50
19 Southwest by south 219.37
21 Southwest by west 236.25
24 West 270.00
25 West by north 286.87
26 West-northwest 286.88
27 Northwest by west 303.75
29 Northwest by north 320.63
30 North-northwest 337.50
0 North 354.38
</pre>
=={{header|JavaScript}}==
===ES5===
|